pyMOR - Model Order Reduction with python¶
pyMOR is a software library for building model order reduction applications with the Python programming language. Implemented algorithms include reduced basis methods for parametric linear and non-linear problems, as well as system-theoretic methods such as balanced truncation or IRKA. All algorithms in pyMOR are formulated in terms of abstract interfaces for seamless integration with external PDE solver packages. Moreover, pure Python implementations of finite element and finite volume discretizations using the NumPy/SciPy scientific computing stack are provided for getting started quickly.
Getting started¶
Installation¶
pyMOR can be easily installed via pip:
pip install --upgrade pip # make sure that pip is reasonably new
pip install pymor[full]
For Linux we provide binary wheels, so no further system packages should be required. The following optional packages must be installed separately:
# for support of MPI distributed models and parallelization of
# greedy algorithms (requires MPI development headers and a C compiler)
pip install mpi4py
# dense matrix equation solver for system-theoretic MOR methods,
# required for H-infinity norm calculation (requires OpenBLAS headers and a Fortran compiler)
pip install slycot
# sparse matrix equation solver for system-theoretic MOR methods
# (other backends available)
open https://www.mpi-magdeburg.mpg.de/projects/mess
# download and install pymess wheel for your architecture
We recommend installation of pyMOR in a virtual environment. Please take a look at our README file for more detailed installation instructions and a guide to setup a development environment for working on pyMOR itself.
Trying it out¶
While we consider pyMOR mainly as a library for building MOR applications, we
ship a few example scripts. These can be found in the src/pymordemos
directory of the source repository (some are available as Jupyter notebooks in
the notebooks directory). Try launching one of them using the pymor-demo
script:
pymor-demo thermalblock --plot-err --plot-solutions 3 2 3 32
The demo scripts can also be launched directly from the source tree:
./thermalblock.py --plot-err --plot-solutions 3 2 3 32
This will reduce the so called thermal block problem using the reduced basis method with a greedy basis generation algorithm. The thermal block problem consists in solving the stationary heat equation
- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = 1 for x in Ω
u(x, μ) = 0 for x in ∂Ω
on the domain Ω = [0,1]^2 for the unknown u. The domain is partitioned into
XBLOCKS x YBLOCKS blocks (XBLOCKS and YBLOCKS are the first
two arguments to thermalblock.py). The thermal conductivity d(x, μ)
is constant on each block (i,j) with value μ_ij:
(0,1)------------------(1,1)
| | | |
| μ_11 | μ_12 | μ_13 |
| | | |
|---------------------------
| | | |
| μ_21 | μ_22 | μ_23 |
| | | |
(0,0)------------------(1,0)
The real numbers μ_ij form the XBLOCKS x YBLOCKS - dimensional parameter
on which the solution depends.
Running thermalblock.py will first produce plots of two detailed
solutions of the problem for different randomly chosen parameters
using linear finite elements. (The size of the grid can be controlled
via the --grid parameter. The randomly chosen parameters will
actually be the same for each run, since a the random generator
is initialized with a fixed default seed in
new_random_state.)
After closing the window, the reduced basis for model order reduction
is generated using a greedy search algorithm with error estimator.
The third parameter SNAPSHOTS of thermalblock.py determines how many
different values per parameter component μ_ij should be considered.
I.e. the parameter training set for basis generation will have the
size SNAPSHOTS^(XBLOCKS x YBLOCKS). After the basis of size 32 (the
last parameter) has been computed, the quality of the obtained reduced model
(on the 32-dimensional reduced basis space) is evaluated by comparing the
solutions of the reduced and detailed models for new, randomly chosen
parameters. Finally, plots of the detailed and reduced solutions, as well
as the difference between the two, are displayed for the random parameter
which maximises reduction error.
The thermalblock demo explained¶
In the following we will walk through the thermal block demo step by
step in an interactive Python shell. We assume that you are familiar
with the reduced basis method and that you know the basics of
Python programming as well as working
with NumPy. (Note that our code will differ a bit from
thermalblock.py as we will hardcode the various options the script
offers and leave out some features.)
First, start a Python shell. We recommend using IPython
ipython
You can paste the following input lines starting with >>> by copying
them to the system clipboard and then executing
%paste
inside the IPython shell.
First, we will import the most commonly used methods and classes of pyMOR by executing:
>>> from pymor.basic import *
Next we will instantiate a class describing the analytical problem
we want so solve. In this case, a
thermal_block_problem:
>>> p = thermal_block_problem(num_blocks=(3, 2))
We want to discretize this problem using the finite element method.
We could do this by hand, creating a Grid, instatiating
DiffusionOperatorP1 finite element diffusion
operators for each subblock of the domain, forming a LincombOperator
to represent the affine decomposition, instantiating a
L2ProductFunctionalP1 as right hand side, and
putting it all together into a StationaryDiscretization. However, since
thermal_block_problem returns
a StationaryProblem, we can use
a predifined discretizer to do the work for us. In this case, we use
discretize_stationary_cg:
>>> d, d_data = discretize_stationary_cg(p, diameter=1./100.)
d is the StationaryDiscretization which has been created for us,
whereas d_data contains some additional data, in particular the Grid
and the BoundaryInfo which have been created during discretization. We
can have a look at the grid,
>>> print(d_data['grid'])
Tria-Grid on domain [0,1] x [0,1]
x0-intervals: 100, x1-intervals: 100
elements: 40000, edges: 60200, vertices: 20201
and, as always, we can display its class documentation using
help(d_data['grid']).
Let’s solve the thermal block problem and visualize the solution:
>>> U = d.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> d.visualize(U, title='Solution')
01:11 StationaryDiscretization: Solving ThermalBlock((3, 2))_CG for {diffusion: [1.0, 0.1, 0.3, 0.1, 0.2, 1.0]} ...
Each class in pyMOR that describes a Parameter dependent mathematical
object, like the StationaryDiscretization in our case, derives from
Parametric and determines the Parameters it expects during __init__
by calling build_parameter_type.
The resulting ParameterType is stored in the object’s
parameter_type attribute. Let us
have a look:
>>> print(d.parameter_type)
{diffusion: (2, 3)}
This tells us, that the Parameter which
solve expects
should be a dictionary with one key 'diffusion' whose value is a
NumPy array of shape (2, 3), corresponding to the block structure of
the problem. However, by using the
parse_parameter method, pyMOR is
smart enough to correctly parse the input [1.0, 0.1, 0.3, 0.1, 0.2, 1.0].
Next we want to use the greedy algorithm
to reduce the problem. For this we need to choose a reductor which will keep
track of the reduced basis and perform the actual RB-projection. We will use
CoerciveRBReductor, which will
also assemble an error estimator to estimate the reduction error. This
will significantly speed up the basis generation, as we will only need to
solve the high-dimensional problem for those parameters in the training set
which are actually selected for basis extension. To control the condition of
the reduced system matrix, we must ensure that the generated basis is
orthonormal w.r.t. the H1_0-product on the solution space. For this we pass
the h1_0_semi_product attribute of the discretization as inner product to
the reductor, which will also use it for computing the Riesz representatives
required for error estimation. Moreover, we have to provide
the reductor with a ParameterFunctional which computes a lower bound for
the coercivity of the problem for a given parameter.
>>> reductor = CoerciveRBReductor(
... d,
... product=d.h1_0_semi_product,
... coercivity_estimator=ExpressionParameterFunctional('min(diffusion)', d.parameter_type)
... )
Moreover, we need to select a Parameter training set. The discretization
d already comes with a ParameterSpace which it has inherited from the
analytical problem. We can sample our parameters from this space, which is a
CubicParameterSpace. E.g.:
>>> samples = d.parameter_space.sample_uniformly(4)
>>> print(samples[0])
{diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}
Now we start the basis generation:
>>> greedy_data = greedy(d, reductor, samples,
... use_estimator=True,
... max_extensions=32)
16:52 greedy: Started greedy search on 4096 samples
16:52 greedy: Reducing ...
16:52 | CoerciveRBReductor: RB projection ...
16:52 | CoerciveRBReductor: Assembling error estimator ...
16:52 | | ResidualReductor: Estimating residual range ...
16:52 | | | estimate_image_hierarchical: Estimating image for basis vector -1 ...
16:52 | | | estimate_image_hierarchical: Orthonormalizing ...
16:52 | | ResidualReductor: Projecting residual operator ...
16:52 greedy: Estimating errors ...
16:55 greedy: Maximum error after 0 extensions: 1.8745731821515579 (mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]})
16:55 greedy: Computing solution snapshot for mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
16:55 | StationaryDiscretization: Solving ThermalBlock((3, 2))_CG for {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
16:55 greedy: Extending basis with solution snapshot ...
...
...
18:57 greedy: Maximum number of 32 extensions reached.
18:57 greedy: Reducing once more ...
18:57 | CoerciveRBReductor: RB projection ...
18:57 | CoerciveRBReductor: Assembling error estimator ...
18:57 | | ResidualReductor: Estimating residual range ...
18:57 | | | estimate_image_hierarchical: Estimating image for basis vector 31 ...
18:57 | | | estimate_image_hierarchical: Orthonormalizing ...
18:57 | | | | gram_schmidt: Removing vector 180 of norm 1.7588304501544013e-15
18:57 | | | | gram_schmidt: Orthonormalizing vector 181 again
18:57 | | | | gram_schmidt: Orthonormalizing vector 182 again
18:57 | | | | gram_schmidt: Orthonormalizing vector 183 again
18:58 | | | | gram_schmidt: Orthonormalizing vector 184 again
18:58 | | | | gram_schmidt: Orthonormalizing vector 185 again
18:58 | | | | gram_schmidt: Orthonormalizing vector 186 again
18:58 | | ResidualReductor: Projecting residual operator ...
18:58 greedy: Greedy search took 126.14163041114807 seconds
The max_extensions parameter defines how many basis vectors we want to
obtain. greedy_data is a dictionary containing various data that has
been generated during the run of the algorithm:
>>> print(greedy_data.keys())
dict_keys(['rd', 'max_errs', 'extensions', 'max_err_mus', 'time'])
The most important items is 'rd' which holds the reduced Discretization
obtained from applying our reductor with the final reduced basis.
>>> rd = greedy_data['rd']
All vectors in pyMOR are stored in so called VectorArrays. For example
the solution U computed above is given as a VectorArray of length 1.
For the reduced basis we have:
>>> print(type(reductor.RB))
<class 'pymor.vectorarrays.numpy.NumpyVectorArray'>
>>> print(len(reductor.RB))
32
>>> print(reductor.RB.dim)
20201
Let us check if the reduced basis really is orthonormal with respect to
the H1-product. For this we use the apply2
method:
>>> import numpy as np
>>> gram_matrix = reductor.RB.gramian(d.h1_0_semi_product)
>>> print(np.max(np.abs(gram_matrix - np.eye(32))))
3.0088616060491846e-14
Looks good! We can now solve the reduced model for the same parameter as above.
The result is a vector of coefficients w.r.t. the reduced basis, which is
currently stored in rb. To form the linear combination, we can use the
reconstruct method of the reductor:
>>> u = rd.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> print(u)
[[ 5.79477471e-01 5.91289054e-02 1.89924036e-01 1.89149529e-02
1.81103127e-01 2.69920752e-02 -1.79611519e-01 7.99676272e-03
1.54092560e-01 5.76326362e-02 1.97982347e-01 -2.13775254e-02
3.12892660e-02 -1.27037440e-01 -1.51352508e-02 3.36101087e-02
2.05779889e-02 -4.96445984e-03 3.21176662e-02 -2.52674851e-02
2.92150040e-02 3.23570362e-03 -4.14288199e-03 5.48325425e-03
4.10728945e-03 1.59251955e-03 -9.23470903e-03 -2.57483574e-03
-2.52451212e-03 -5.08125873e-04 2.71427033e-03 5.83210112e-05]]
>>> U_red = reductor.reconstruct(u)
>>> print(U_red.dim)
20201
Finally we compute the reduction error and display the reduced solution along with the detailed solution and the error:
>>> ERR = U - U_red
>>> print(ERR.norm(d.h1_0_semi_product))
[0.00473238]
>>> d.visualize((U, U_red, ERR),
... legend=('Detailed', 'Reduced', 'Error'),
... separate_colorbars=True)
We can nicely observe that, as expected, the error is maximized along the jumps of the diffusion coefficient.
Learning more¶
As a next step, you should read our Technical Overview which discusses the most important concepts and design decisions behind pyMOR. After that you should be ready to delve into the reference documentation.
Should you have any problems regarding pyMOR, questions or feature requests, do not hesitate to contact us at our mailing list!
Technical Overview¶
Three Central Classes¶
From a bird’s eye perspective, pyMOR is a collection of generic algorithms operating on objects of the following types:
VectorArraysVector arrays are ordered collections of vectors. Each vector of the array must be of the same
dimension. Vectors can becopiedto a new array,appendedto an existing array ordeletedfrom the array. Basic linear algebra operations can be performed on the vectors of the array: vectors can bescaledin-place, the BLASaxpyoperation is supported andinner productsbetween vectors can be formed. Linear combinations of vectors can be formed using thelincombmethod. Moreover, various norms can be computed and selecteddofsof the vectors can be extracted forempirical interpolation. To act on subsets of vectors of an array, arrays can beindexedwith an integer, a list of integers or a slice, in each case returning a newVectorArraywhich acts as a modifiable view onto the respective vectors in the original array. As a convenience, many of Python’s math operators are implemented in terms of the interface methods.Note that there is not the notion of a single vector in pyMOR. The main reason for this design choice is to take advantage of vectorized implementations like
NumpyVectorArraywhich internally store the vectors as two-dimensionalNumPyarrays. As an example, the application of a linear matrix based operator to an array via theapplymethod boils down to a call toNumPy’s optimizeddotmethod. If there were only lists of vectors in pyMOR, the above matrix-matrix multiplication would have to be expressed by a loop of matrix-vector multiplications. However, when working with external solvers, vector arrays will often be given as lists of individual vector objects. For this use-case we provideListVectorArray, aVectorArraybased on a Python list of vectors.Associated to each vector array is a
VectorSpacewhich acts as a factory for new arrays of a given type. New vector arrays can be created using thezerosandemptymethods. To wrap the raw objects of the underlying linear algebra backend into a newVectorArray,make_arrayis used.The data needed to define a new
VectorSpacelargely depends on the implementation of the underlying backend. ForNumpyVectorSpace, the only required datum is the dimension of the contained vectors.VectorSpacesfor other backends could, e.g., hold a socket for communication with a specific PDE solver instance. Additionally, eachVectorSpacehas a stringid, defaulting toNone, which is used to signify the mathematical identity of the given space.Two arrays in pyMOR are compatible (e.g. can be added) if they are from the same
VectorSpace. If aVectorArrayis contained in a givenVectorSpacecan be tested with theinoperator.OperatorsThe main property of operators in pyMOR is that they can be
appliedtoVectorArraysresulting in a newVectorArray. For this operation to be allowed, the operator’ssourceVectorSpacemust be identical with theVectorSpaceof the given array. The result will be a vector array from therangespace. An operator can belinearor not. Theapply_inversemethod provides an interface for (linear) solvers.Operators in pyMOR are also used to represent bilinear forms via the
apply2method. A functional in pyMOR is simply an operator withNumpyVectorSpace(1)asrange. Dually, a vector-like operator is an operator withNumpyVectorSpace(1)assource. Such vector-like operators are used in pyMOR to representParameterdependent vectors such as the initial data of anInstationaryDiscretization. For linear functionals and vector-like operators, theas_vectormethod can be called to obtain a vector representation of the operator as aVectorArrayof length 1.Linear combinations of operators can be formed using a
LincombOperator. When such a linear combination isassembled,assemble_lincombis called to ensure that, for instance, linear combinations of operators represented by a matrix lead to a new operator holding the linear combination of the matrices.Default implementations for many methods of the operator interface can be found in
OperatorBase. Base classes forNumPy-based operators can be found inpymor.operators.numpy. Several methods for constructing new operators from existing ones are contained inpymor.operators.constructions.DiscretizationsDiscretizations in pyMOR encode the mathematical structure of a given discrete problem by acting as container classes for operators. Each discretization object has
operators,productsdictionaries holding theOperatorswhich appear in the formulation of the discrete problem. The keys in these dictionaries describe the role of the respective operator in the discrete problem.Apart from describing the discrete problem, discretizations also implement algorithms for
solvingthe given problem, returningVectorArraysfrom thesolution_space. The solution can becached, s.t. subsequent solving of the problem for the same parameter reduces to looking up the solution in pyMOR’s cache.While special discretization classes may be implemented which make use of the specific types of operators they contain (e.g. using some external high-dimensional solver for the problem), it is generally favourable to implement the solution algorithms only through the interfaces provided by the operators contained in the discretization, as this allows to use the same discretization class to solve high-dimensional and reduced problems. This has been done for the simple stationary and instationary discretizations found in
pymor.discretizations.basic.Discretizations can also implement
estimateandvisualizemethods to estimate the discretization or model reduction error of a computed solution and create graphic representations ofVectorArraysfrom thesolution_space.
Base Classes¶
While VectorArrays are mutable objects, both Operators and Discretizations
are immutable in pyMOR: the application of an Operator to the same
VectorArray will always lead to the same result, solving a Discretization
for the same parameter will always produce the same solution array. This has two
main benefits:
- If multiple objects/algorithms hold references to the same
OperatororDiscretization, none of the objects has to worry that the referenced object changes without their knowledge. - It becomes affordable to generate persistent keys for
cachingof computation results by generating state ids which uniquely identify the object’s state. Since the state cannot change, these ids have to be computed only once for the lifetime of the object.
A class can be made immutable in pyMOR by deriving from ImmutableInterface,
which ensures that write access to the object’s attributes is prohibited after
__init__ has been executed. However, note that changes to private attributes
(attributes whose name starts with _) are still allowed. It lies in the
implementors responsibility to ensure that changes to these attributes do not
affect the outcome of calls to relevant interface methods. As an example, a call
to enable_caching will set the
objects private __cache_region attribute, which might affect the speed of a
subsequent solve call, but not its result.
Of course, in many situations one may wish to change properties of an immutable
object, e.g. the number of timesteps for a given discretization. This can be
easily achieved using the
with_ method every immutable
object has: a call of the form o.with_(a=x, b=y) will return a copy of o
in which the attribute a now has the value x and the attribute b the
value y. It can be generally assumed that calls to
with_ are inexpensive. The
set of allowed arguments can be found in the
with_arguments attribute.
All immutable classes in pyMOR and most other classes derive from
BasicInterface which, through its meta class, provides several convenience
features for pyMOR. Most notably, every subclass of BasicInterface obtains its
own logger instance with a class
specific prefix.
Creating Discretizations¶
pyMOR ships a small (and still quite incomplete) framework for creating finite
element or finite volume discretizations based on the NumPy/Scipy software stack. To end up with an appropriate
Discretization, one starts by instantiating an analytical problem which
describes the problem we want to discretize. analytical problems contain
Functions which define the analytical data functions associated with the
problem and a DomainDescription that provides a geometrical definition of the
domain the problem is posed on and associates a boundary type to each part of
its boundary.
To obtain a Discretization from an analytical problem we use a
discretizer. A discretizer will first mesh the
computational domain by feeding the DomainDescription into a
domaindiscretizer which will return the Grid
along with a BoundaryInfo associating boundary entities with boundary types.
Next, the Grid, BoundaryInfo and the various data functions of the
analytical problem are used to instatiate finite element or finite volume operators.
Finally these operators are used to instatiate one of the provided
Discretization classes.
In pyMOR, analytical problems, Functions, DomainDescriptions,
BoundaryInfos and Grids are all immutable, enabling efficient
disk caching for the resulting Discretizations, persistent over various
runs of the applications written with pyMOR.
While pyMOR’s internal discretizations are useful for getting started quickly
with model reduction experiments, pyMOR’s main goal is to allow the reduction of
discretizations provided by external solvers. In order to do so, all that needs
to be done is to provide VectorArrays, Operators and Discretizations which
interact appropriately with the solver. pyMOR makes no assumption on how the
communication with the solver is managed. For instance, communication could take
place via a network protocol or job files. In particular it should be stressed
that in general no communication of high-dimensional data between the solver
and pyMOR is necessary: VectorArrays can merely hold handles to data in the
solver’s memory or some on-disk database. Where possible, we favour, however, a
deep integration of the solver with pyMOR by linking the solver code as a Python
extension module. This allows Python to directly access the solver’s data
structures which can be used to quickly add features to the high-dimensional
code without any recompilation. A minimal example for such an integration using
pybindgen can be found in the
src/pymordemos/minimal_cpp_demo directory of the pyMOR repository.
Bindings for FEnicS and
NGSolve packages are available in the
bindings.fenics and
bindings.ngsolve modules.
The pymor-deal.II repository contains
experimental bindings for deal.II.
Parameters¶
pyMOR classes implement dependence on a parameter by deriving from the
Parametric mix-in class. This class gives each instance a
parameter_type attribute describing the
form of Parameters the relevant methods of the object (apply, solve,
evaluate, etc.) expect. A Parameter in pyMOR is basically a Python
dict with strings as keys and NumPy arrays as values. Each such value
is called a Parameter component. The ParameterType of a Parameter is
simply obtained by replacing the arrays in the Parameter with their shape.
I.e. a ParameterType specifies the names of the parameter components and their
expected shapes.
The ParameterType of a Parametric object is determined by the class
implementor during __init__ via a call to
build_parameter_type, which can be
used to infer the ParameterType from the ParameterTypes of objects the
given object depends upon. I.e. an Operator implementing the L2-product with
some Function will inherit the ParameterType of the Function.
Reading the reference documentation on pyMOR’s
parameter handling facilities is strongly advised for implementors of
Parametric classes.
Defaults¶
pyMOR offers a convenient mechanism for handling default values such as solver
tolerances, cache sizes, log levels, etc. Each default in pyMOR is the default
value of an optional argument of some function. Such an argument is made a
default by decorating the function with the defaults
decorator:
@defaults('tolerance')
def some_algorithm(x, y, tolerance=1e-5)
...
Default values can be changed by calling set_defaults.
By calling print_defaults a summary of all defaults
in pyMOR and their values can be printed. A configuration file with all defaults
can be obtained with write_defaults_to_file. This file can
then be loaded, either programmatically or automatically by setting the
PYMOR_DEFAULTS environment variable.
As an additional feature, if None is passed as value for a function argument
which is a default, its default value is used instead of None. This allows
writing code of the following form:
def method_called_by_user(U, V, tolerance_for_algorithm=None):
...
algorithm(U, V, tolerance=tolerance_for_algorithm)
...
See the defaults module for more information.
RuleTables¶
Many algorithms in pyMOR can be seen as transformations acting on trees of
Operators. One example is the structure-preserving (Petrov-)Galerkin
projection of Operators performed by the project method. For instance, a
LincombOperator is projected by replacing all its children (the Operators
forming the affine decomposition) with projected Operators.
During development of pyMOR, it turned out that using inheritance for selecting
the action to be taken to project a specific operator (i.e. single dispatch
based on the class of the to-be-projected Operator) is not sufficiently
flexible. With pyMOR 0.5 we have introduced algorithms which are based on
RuleTables instead of inheritance. A RuleTable is simply an ordered list of
rules, i.e. pairs of conditions to match
with corresponding actions. When a RuleTable is applied to an object (e.g. an Operator),
the action associated with the first matching rule in the table is executed. As
part of the action, the RuleTable can be easily applied recursively to the children of the given
object.
This approach has several advantages over an inheritance-based model:
- Rules can match based on the class of the object, but also on more general
conditions, i.e. the name of the
Operatoror being linear and non-parametric. - The entire mathematical algorithm can be specified in a single file even when the definition of the possible classes the algorithm can be applied to is scattered over various files.
- The precedence of rules is directly apparent from the definition of the
RuleTable. - Generic rules (e.g. the projection of a linear non-
parametricOperatorby simply applying the basis) can be easily scheduled to take precedence over more specific rules. - Users can implement or modify
RuleTableswithout modification of the classes shipped with pyMOR.
The Reduction Process¶
The reduction process in pyMOR is handled by so called reductors
which take arbitrary Discretizations and additional data (e.g. the reduced
basis) to create reduced Discretizations. If proper offline/online
decomposition is achieved by the reductor, the reduced Discretization will
not store any high-dimensional data. Note that there is no inherent distinction
between low- and high-dimensional Discretizations in pyMOR. The only
difference lies in the different types of operators, the Discretization
contains.
This observation is particularly apparent in the case of the classical
reduced basis method: the operators and functionals of a given discrete problem
are projected onto the reduced basis space whereas the structure of the problem
(i.e. the type of Discretization containing the operators) stays the same.
pyMOR reflects this fact by offering with GenericRBReductor
a generic algorithm which can be used to RB-project any discretization available to pyMOR.
It should be noted however that this reductor is only able to efficiently
offline/online-decompose affinely Parameter-dependent linear problems.
Non-linear problems or such with no affine Parameter dependence require
additional techniques such as empirical interpolation.
If you want to further dive into the inner workings of pyMOR, we highly
recommend to study the source code of GenericRBReductor
and to step through calls of this method with a Python debugger, such as
ipdb.
Environment Variables¶
pyMOR respects the following environment variables:
- PYMOR_CACHE_DISABLE
- If
1, disable caching globally, overriding calls toenable_caching. This is mainly useful for debugging. Seepymor.core.cachefor more details. - PYMOR_COLORS_DISABLE
- If
1, disable coloring of logging output. - PYMOR_WITH_SPHINX
- This variable is set to
1during API documentation generation using sphinx. - PYMOR_DEFAULTS
- If empty or
NONE, do not load anydefaultsfrom file. Otherwise, a:-separated list of the paths to a Python scripts containing defaults.
Release Notes¶
pyMOR 0.5 (January 17, 2019)¶
After more than two years of development, we are proud to announce the release
of pyMOR 0.5! Highlights of this release are support for Python 3, bindings for
the NGSolve finite element library, new linear algebra algorithms, various
VectorArray usability improvements, as well as a redesign of pyMOR’s
projection algorithms based on RuleTables.
Especially we would like to highlight the addition of various system-theoretic
reduction methods such as Balanced Truncation or IRKA. All algorithms are
implemented in terms of pyMOR’s Operator and VectorArray interfaces,
allowing their application to any model implemented using one of the PDE solver
supported by pyMOR. In particular, no import of the system matrices is
required.
Over 1,500 single commits have entered this release. For a full list of changes see here.
pyMOR 0.5 contains contributions by Linus Balicki, Julia Brunken and Christoph Lehrenfeld. See here for more details.
Release highlights¶
Python 3 support¶
pyMOR is now compatible with Python 3.5 or greater. Since the use of Python 3 is
now standard in the scientific computing community and security updates for
Python 2 will stop in less than a year (https://pythonclock.org), we decided to
no longer support Python 2 and make pyMOR 0.5 a Python 3-only release. Switching
to Python 3 also allows us to leverage newer language features such as the @
binary operator for concatenation of Operators, keyword-only arguments or
improved support for asynchronous programming.
System-theoretic MOR methods¶
With 386 commits, [#464] added
systems-theoretic methods to pyMOR. Module pymor.discretizations.iosys
contains new discretization classes for input-output systems, e.g. LTISystem,
SecondOrderSystem and TransferFunction. At present, methods related to these
classes mainly focus on continuous-time, non-parametric systems.
Since matrix equation solvers are important tools in many system-theoretic
methods, support for Lyapunov, Riccati and Sylvester equations has been added in
pymor.algorithms.lyapunov, pymor.algorithms.riccati and
pymor.algorithms.sylvester. A generic low-rank ADI (Alternating Direction
Implicit) solver for Lyapunov equations is implemented in
pymor.algorithms.lradi. Furthermore, bindings to low-rank and dense
solvers for Lyapunov and Riccati equations from SciPy,
Slycot and
Py-M.E.S.S. are provided in
pymor.bindings.scipy, pymor.bindings.slycot and
pymor.bindings.pymess. A generic Schur decomposition-based solver for
sparse-dense Sylvester equations is implemented in
pymor.algorithms.sylvester.
Balancing Truncation (BT) and Iterative Rational Krylov Algorithm (IRKA) are
implemented in BTReductor and
IRKAReductor. LQG and Bounded Real variants of BT
are also available (LQGBTReductor,
BRBTReductor). Bitangential Hermite interpolation
(used in IRKA) is implemented in
LTI_BHIReductor. Two-Sided Iteration
Algorithm (TSIA), a method related to IRKA, is implemented in
TSIAReductor.
Several structure-preserving MOR methods for second-order systems have been
implemented. Balancing-based MOR methods are implemented in
pymor.reductors.sobt, bitangential Hermite interpolation in
SO_BHIReductor and Second-Order Reduced
IRKA (SOR-IRKA) in SOR_IRKAReductor.
For more general transfer functions, MOR methods which return LTISystems are
also available. Bitangential Hermite interpolation is implemented in
TFInterpReductor and Transfer Function
IRKA (TF-IRKA) in TF_IRKAReductor.
Usage examples can be found in the heat and string_equation demo scripts.
NGSolve support¶
We now ship bindings for the NGSolve finite element
library. Wrapper classes for VectorArrays and matrix-based Operators can be
found in the pymor.bindings.ngsolve module. A usage example can be found
in the thermalblock_simple demo script.
New linear algebra algorithms¶
pyMOR now includes an implementation of the
HAPOD algorithm for fast distributed
or incremental computation of the Proper Orthogonal Decomposition
(pymor.algorithms.hapod). The code allows for arbitrary sub-POD trees,
on-the-fly snapshot generation and shared memory parallelization via
concurrent.futures. A basic usage example can be found in the hapod
demo script.
In addition, the Gram-Schmidt biorthogonalization algorithm has been included in
pymor.algorithms.gram_schmidt.
VectorArray improvements¶
VectorArrays in pyMOR have undergone several usability improvements:
- The somewhat dubious concept of a
subtypehas been superseded by the concept ofVectorSpaceswhich act as factories forVectorArrays. In particular, instead of asubtype,VectorSpacescan now hold meaningful attributes (e.g. the dimension) which are required to constructVectorArrayscontained in the space. Theidattribute allows to differentiate between technically identical but mathematically different spaces [#323]. VectorArrayscan now be indexed to select a subset of vectors to operate on. In contrast to advanced indexing inNumPy, indexing aVectorArraywill always return a view onto the original array data [#299].- New methods with clear semantics have been introduced for the conversion of
VectorArraysto (to_numpy) and from (from_numpy)NumPy arrays[#446]. - Inner products between
VectorArraysw.r.t. to a given inner productOperatoror their norm w.r.t. such an operator can now easily be computed by passing theOperatoras the optionalproductargument to the newinnerandnormmethods [#407]. - The
componentsmethod ofVectorArrayshas been renamed to the more intuitive namedofs[#414]. - The
l2_norm2andnorm2have been introduced to compute the squared vector norms [#237].
RuleTable based algorithms¶
In pyMOR 0.5, projection algorithms are implemented via recursively applied
tables of transformation rules. This replaces the previous inheritance-based
approach. In particular, the projected method to perform a (Petrov-)Galerkin
projection of an arbitrary Operator has been removed and replaced by a free
project function. Rule-based algorithms are implemented by deriving from the
RuleTable base class [#367],
[#408].
This approach has several advantages:
- Rules can match based on the class of the object, but also on more general
conditions, e.g. the name of the
Operatoror being linear and non-parametric. - The entire mathematical algorithm can be specified in a single file even when the definition of the possible classes the algorithm can be applied to is scattered over various files.
- The precedence of rules is directly apparent from the definition of the
RuleTable. - Generic rules (e.g. the projection of a linear non-
parametricOperatorby simply applying the basis) can be easily scheduled to take precedence over more specific rules. - Users can implement or modify
RuleTableswithout modification of the classes shipped with pyMOR.
Additional new features¶
Reduction algorithms are now implemented using mutable reductor objects, e.g.
GenericRBReductor, which store andextendthe reduced bases onto which the model is projected. The only return value of the reductor’sreducemethod is now the reduced discretization. Instead of a separate reconstructor, the reductor’sreconstructmethod can be used to reconstruct a high-dimensional state-space representation. Additional reduction data (e.g. used to speed up repeated reductions in greedy algorithms) is now managed by the reductor [#375].Linear combinations and concatenations of
Operatorscan now easily be formed using arithmetic operators [#421].The handling of complex numbers in pyMOR is now more consistent. See [#458], [#362], [#447] for details. As a consequence of these changes, the
rhsOperatorinStationaryDiscretizationis now a vector-likeOperatorinstead of a functional.The analytical problems and discretizers of pyMOR’s discretization toolbox have been reorganized and improved. All problems are now implemented as instances of
StationaryProblemorInstationaryProblem, which allows an easy exchange of dataFunctionsof a predefined problem with user-definedFunctions. Affine decomposition ofFunctionsis now represented by specifying aLincombFunctionas the respective data function [#312], [#316], [#318], [#337].The
pymor.core.configmodule allows simple run-time checking of the availability of optional dependencies and their versions [#339].Packaging improvements
A compiler toolchain is no longer necessary to install pyMOR as we are now distributing binary wheels for releases through the Python Package Index (PyPI). Using the
extras_requiremechanism the user can select to install either a minimal set:pip install pymor
or almost all, including optional, dependencies:
pip install pymor[full]
A docker image containing all of the discretization packages pyMOR has bindings to is available for demonstration and development purposes:
docker run -it pymor/demo:0.5 pymor-demo -h docker run -it pymor/demo:0.5 pymor-demo thermalblock --fenics 2 2 5 5
Backward incompatible changes¶
dim_outerhas been removed from the grid interface [#277].- All wrapper code for interfacing with external PDE libraries or equation
solvers has been moved to the
pymor.bindingspackage. For instance,FenicsMatrixOperatorcan now be found in thepymor.bindings.fenicsmodule. [#353] - The
sourceandrangearguments of the constructor ofZeroOperatorhave been swapped to comply with related function signatures [#415]. - The identifiers
discretization,rb_discretization,ei_discretizationhave been replaced byd,rd,ei_dthroughout pyMOR [#416]. - The
_matrixattribute ofNumpyMatrixOperatorhas been renamed tomatrix[#436]. Ifmatrixholds aNumPy arraythis array is automatically made read-only to prevent accidental modification of theOperator[#462]. - The
BoundaryTypeclass has been removed in favor of simple strings [#305]. - The complicated and unused mapping of local parameter component names to global names has been removed [#306].
Further notable improvements¶
- [#176] Support different colormaps in GLPatchWidget.
- [#238] From Operator to NumPy operator.
- [#308] Add NumpyGenericOperator.apply_adjoint.
- [#313] Add finiteness checks to linear solvers.
- [#314] [ExpressionFunction] add components of mu to locals.
- [#315] [functions] some improvements to ExpressionFunction/GenericFunction.
- [#338] Do not print version string on import.
- [#346] Implement more arithmetic operations on VectorArrays and Operators.
- [#348] add InverseOperator and InverseTransposeOperator.
- [#359] [grids] bugfix for boundary handling in subgrid.
- [#365] [operators] add ProxyOperator.
- [#366] [operators] add LinearOperator and AffineOperator.
- [#368] Add support for PyQt4 and PyQt5 by using Qt.py shim.
- [#369] Add basic support for visualization in juypter notebooks.
- [#370] Let BitmapFunction accept non-grayscale images.
- [#382] Support mpi4py > 2.0.
- [#401] [analyticalproblems] add text_problem.
- [#410] add relative_error and project_array functions.
- [#422] [Concatenation] allow more than two operators in a Concatenation.
- [#425] [ParameterType] base implementation on OrderedDict.
- [#431] [operators.cg] fix first order integration.
- [#437] [LincombOperator] implement ‘apply_inverse’.
- [#438] Fix VectorArrayOperator, generalize as_range/source_array.
- [#441] fix #439 (assemble_lincomb “operators” parameter sometimes list, sometimes tuple).
- [#452] Several improvements to pymor.algorithms.ei.deim.
- [#453] Extend test_assemble.
- [#480| [operators] Improve subtraction of LincombOperators.
- [#481] [project] ensure solver_options are removed from projected operators.
- [#484] [docs] move all references to bibliography.rst.
- [#488] [operators.block] add BlockRowOperator, BlockColumnOperator.
- [#489] Output functionals in CG discretizations.
- [#497] Support automatic conversion of InstationaryDiscretization to LTISystem.
pyMOR 0.4 (September 28, 2016)¶
With the pyMOR 0.4 release we have changed the copyright of pyMOR to
Copyright 2013-2016 pyMOR developers and contributors. All rights reserved.
Moreover, we have added a Contribution guideline to help new users with starting to contribute to pyMOR. Over 800 single commits have entered this release. For a full list of changes see here. pyMOR 0.4 contains contributions by Andreas Buhr, Michael Laier, Falk Meyer, Petar Mlinarić and Michael Schaefer. See here for more details.
Release highlights¶
FEniCS and deal.II support¶
pyMOR now includes wrapper classes for integrating PDE solvers
written with the dolfin library of the FEniCS
project. For a usage example, see pymordemos.thermalblock_simple.discretize_fenics.
Experimental support for deal.II can be
found in the pymor-deal.II
repository of the pyMOR GitHub organization.
Parallelization of pyMOR’s reduction algorithms¶
We have added a parallelization framework to pyMOR which allows
parallel execution of reduction algorithms based on a simple
WorkerPool interface [#14].
The greedy [#155]
and ei_greedy algorithms [#162]
have been refactored to utilize this interface.
Two WorkerPool implementations are shipped with pyMOR:
IPythonPool utilizes the parallel
computing features of IPython, allowing
parallel algorithm execution in large heterogeneous clusters of
computing nodes. MPIPool can be used
to benefit from existing MPI-based parallel HPC computing architectures
[#161].
Support classes for MPI distributed external PDE solvers¶
While pyMOR’s VectorArray, Operator and Discretization
interfaces are agnostic to the concrete (parallel) implementation
of the corresponding objects in the PDE solver, external solvers
are often integrated by creating wrapper classes directly corresponding
to the solvers data structures. However, when the solver is executed
in an MPI distributed context, these wrapper classes will then only
correspond to the rank-local data of a distributed VectorArray or
Operator.
To facilitate the integration of MPI parallel solvers, we have added
MPI helper classes [#163]
in pymor.vectorarrays.mpi, pymor.operators.mpi
and pymor.discretizations.mpi that allow an automatic
wrapping of existing sequential bindings for MPI distributed use.
These wrapper classes are based on a simple event loop provided
by pymor.tools.mpi, which is used in the interface methods of
the wrapper classes to dispatch into MPI distributed execution
of the corresponding methods on the underlying MPI distributed
objects.
The resulting objects can be used on MPI rank 0 (including interactive
Python sessions) without any further changes to pyMOR or the user code.
For an example, see pymordemos.thermalblock_simple.discretize_fenics.
New reduction algorithms¶
adaptive_greedyuses adaptive parameter training set refinement according to [HDO11] to prevent overfitting of the reduced model to the training set [#213].reduce_parabolicreduces linear parabolic problems usingreduce_generic_rband assembles an error estimator similar to [GP05], [HO08]. Theparabolic_mordemo contains a simple sample application using this reductor [#190].- The
estimate_imageandestimate_image_hierarchicalalgorithms can be used to find an as small as possible space in which the images of a given list of operators for a given source space are contained for all possible parametersmu. For possible applications, seereduce_residualwhich now usesestimate_image_hierarchicalfor Petrov-Galerkin projection of the residual operator [#223].
Copy-on-write semantics for VectorArrays¶
The copy method
of the VectorArray interface is now assumed to have copy-on-write
semantics. I.e., the returned VectorArray will contain a reference to the same
data as the original array, and the actual data will only be copied when one of
the arrays is changed. Both NumpyVectorArray and ListVectorArray have been
updated accordingly [#55].
As a main benefit of this approach, immutable objects having a VectorArray as
an attribute now can safely create copies of the passed VectorArrays (to ensure
the immutability of their state) without having to worry about unnecessarily
increased memory consumption.
Improvements to pyMOR’s discretizaion tookit¶
- An unstructured triangular
Gridis now provided byUnstructuredTriangleGrid. Such aGridcan be obtained using thediscretize_gmshmethod, which can parse Gmsh output files. Moreover, this method can generateGmshinput files to create unstructured meshes for an arbitraryPolygonalDomain[#9]. - Basic support for parabolic problems has been added.
The
discretize_parabolic_cganddiscretize_parabolic_fvmethods can be used to build continuous finite element or finite volumeDiscretizationsfrom a givenpymor.analyticalproblems.parabolic.ParabolicProblem. Theparabolicdemo demonstrates the use of these methods [#189]. - The
pymor.discretizers.diskmodule contains methods to create stationary and instationary affinely decomposedDiscretizationsfrom matrix data files and an.inifile defining the given problem. EllipticProblemscan now also contain advection and reaction terms in addition to the diffusion part.discretize_elliptic_cghas been extended accordingly [#211].- The
continuous Galerkinmodule has been extended to support Robin boundary conditions [#110]. BitmapFunctionallows to use grayscale image data as dataFunctions[#194].- For the visualization of time-dependent data, the colorbars can now be rescaled with each new frame [#91].
Caching improvements¶
- state id generation is now based on deterministic pickling.
In previous version of pyMOR, the state id of
immutableobjects was computed from the state ids of the parameters passed to the object’s__init__method. This approach was complicated and error-prone. Instead, we now compute the state id as a hash of a deterministic serialization of the object’s state. While this approach is more robust, it is also slightly more expensive. However, due to the object’s immutability, the state id only has to be computed once, and state ids are now only required for storing results in persistent cache regions (see below). Computing such results will usually be much more expensive than the state id calculation [#106]. CacheRegionsnow have apersistentattribute indicating whether the cache data will be kept between program runs. For persistent cache regions the state id of the object for which the cached method is called has to be computed to obtain a unique persistent id for the given object. For non-persistent regions the object’suidcan be used instead.pymor.core.cache_regionsnow by default contains'memory','disk'and'persistent'cache regions [#182], [#121] .defaultscan now be marked to not affect state id computation. In previous version of pyMOR, changing anydefaultvalue caused a change of the state id pyMOR’s defaults dictionary, leading to cache misses. While this in general is desirable, as, for instance, changed linear solver default error tolerances might lead to different solutions for the sameDiscretizationobject, it is clear for many I/O related defaults, that these will not affect the outcome of any computation. For these defaults, thedefaultsdecorator now accepts asid_ignoreparameter, to exclude these defaults from state id computation, preventing changes of these defaults causing cache misses [#81].- As an alternative to using the
@cacheddecorator,cached_method_callcan be used to cache the results of a function call. This is now used insolveto enable parsing of the input parameter before it enters the cache key calculation [#231].
Additional new features¶
apply_inverse_adjointhas been added to theOperatorinterface [#133].- Support for complex values in
NumpyVectorArrayandNumpyMatrixOperator[#131]. - New
ProductParameterFunctional. - This
ParameterFunctionalrepresents the product of a given list ofParameterFunctionals.
- New
- New
SelectionOperator[#105]. - This
Operatorrepresents oneOperatorof a given list ofOperators, depending on the evaluation of a providedParameterFunctional,
- New
- New block matrix operators [#215].
BlockOperatorandBlockDiagonalOperatorrepresent block matrices ofOperatorswhich can be applied to appropriately shapedBlockVectorArrays.
from_filefactory method forNumpyVectorArrayandNumpyMatrixOperator[#118].NumpyVectorArray.from_fileandNumpyMatrixOperator.from_filecan be used to construct such objects from data files of various formats (MATLAB, matrix market, NumPy data files, text).
ListVectorArray-basedNumpyMatrixOperator[#164].- The
playgroundnow containsNumpyListVectorArrayMatrixOperatorwhich can applyNumPy/SciPymatrices to aListVectorArray. ThisOperatoris mainly intended for performance testing purposes. Thethermalblockdemo now has an option--list-vector-arrayfor using this operator instead ofNumpyMatrixOperator.
- Log indentation support [#230].
- pyMOR’s log output can now be indented via the
logger.block(msg)context manger to reflect the hierarchy of subalgorithms.
- Default implementation of
as_vectorfor functionals [#107]. OperatorBase.as_vectornow contains a default implementation for functionals by callingapply_adjoint.
- Default implementation of
pycontractshas been removed as a dependency of pyMOR [#127].- Test coverage has been raised to 80 percent.
Backward incompatible changes¶
VectorArrayimplementations have been moved to thepymor.vectorarrayssub-package [#89].- The
dotmethod of theVectorArrayinterface has been split intodotandpairwise_dot[#76]. - The
pairwiseparameter ofdothas been removed, always assumingpairwise == False. The methodpairwise_dotcorresponds to thepairwise == Truecase. Similarly thepariwiseparameter of theapply2method of theOperatorinterface has been removed and apairwise_apply2method has been added.
- The
almost_equalhas been removed from theVectorArrayinterface [#143].- As a replacement, the new method
pymor.algorithms.basic.almost_equalcan be used to compareVectorArraysfor almost equality by the norm of their difference.
lincombhas been removed from theOperatorinterface [#83].- Instead, a
LincombOperatorshould be directly instantiated.
- Removal of the
optionsparameter ofapply_inversein favor ofsolver_optionsattribute [#122]. - The
optionsparameter ofOperatorInterface.apply_inversehas been replaced by thesolver_optionsattribute. This attribute controls which fixed (linear) solver options are used whenapply_inverseis called. See here for more details.
- Removal of the
- Renaming of reductors for coercive problems [#224].
pymor.reductors.linear.reduce_stationary_affine_linearandpymor.reductors.stationary.reduce_stationary_coercivehave been renamed topymor.reductors.coercive.reduce_coerciveandpymor.reductors.coercive.reduce_coercive_simple. The old names are deprecated and will be removed in pyMOR 0.5.
- Non-parametric objects have now
parameter_type{}instead ofNone[#84]. - Sampling methods of
ParameterSpacesnow return iterables instead of iterators [#108]. - Caching of
solveis now disabled by default [#178]. - Caching of
solvemust now be explicitly enabled by usingpymor.core.cache.CacheableInterface.enable_caching.
- Caching of
- The default value for
extension_algorithmparameter ofgreedyhas been removed [#82]. - Changes to
ei_greedy[#159], [#160]. - The default for the
projectionparameter has been changed from'orthogonal'to'ei'to let the default algorithm agree with literature. In addition acopyparameter with defaultTruehas been added. WhencopyisTrue, the input data is copied before executing the algorithm, ensuring, that the originalVectorArrayis left unchanged. When possible,copyshould be set toFalsein order to reduce memory consumption.
- Changes to
- The
copyparameter ofpymor.algorithms.gram_schmidt.gram_schmidtnow defaults toTrue[#123]. with_has been moved fromBasicInterfacetoImmutableInterface[#154].BasicInterface.add_attributeshas been removed [#158].- Python fallbacks to Cython functions have been removed [#145].
- In order to use pyMOR’s discretization toolkit, building of the
_unstructured,inplace,relationsCython extension modules is now required.
Further improvements¶
- [#78] update apply_inverse signature
- [#115] [algorithms.gram_schmidt] silence numpy warning
- [#144] L2ProductP1 uses wrong quadrature rule in 1D case
- [#147] Debian doc packages have weird title
- [#151] add tests for ‘almost_equal’ using different norms
- [#156] Let thermal block demo use error estimator by default
- [#195] Add more tests / fixtures for operators in pymor.operators.constructions
- [#197] possible problem in caching
- [#207] No useful error message in case PySide.QtOpenGL cannot be imported
- [#209] Allow ‘pip install pymor’ to work even when numpy/scipy are not installed yet
- [#219] add minimum versions for dependencies
- [#228] merge fixes in python3 branch back to master
- [#269] Provide a helpful error message when cython modules are missing
- [#276] Infinite recursion in apply for IdentityOperator * scalar
pyMOR 0.3 (March 2, 2015)¶
- Introduction of the vector space concept for even simpler integration with external solvers.
- Addition of a generic Newton algorithm.
- Support for Jacobian evaluation of empirically interpolated operators.
- Greatly improved performance of the EI-Greedy algorithm. Addition of the DEIM algorithm.
- A new algorithm for residual operator projection and a new, numerically stable a posteriori error estimator for stationary coercive problems based on this algorithm. (cf. A. Buhr, C. Engwer, M. Ohlberger, S. Rave, ‘A numerically stable a posteriori error estimator for reduced basis approximations of elliptic equations’, proceedings of WCCM 2014, Barcelona, 2014.)
- A new, easy to use mechanism for setting and accessing default values.
- Serialization via the pickle module is now possible for each class in pyMOR. (See the new ‘analyze_pickle’ demo.)
- Addition of generic iterative linear solvers which can be used in conjunction with any operator satisfying pyMOR’s operator interface. Support for least squares solvers and PyAMG (http://www.pyamg.org/).
- An improved SQLite-based cache backend.
- Improvements to the built-in discretizations: support for bilinear finite elements and addition of a finite volume diffusion operator.
- Test coverage has been raised from 46% to 75%.
Over 500 single commits have entered this release. A full list of all changes can be obtained under the following address: https://github.com/pymor/pymor/compare/0.2.2…0.3.0
Bibliography¶
| [A05] | A. C. Antoulas, Approximation of Large-Scale Dynamical Systems, SIAM, 2005. |
| [ABG10] | A. C. Antoulas, C. A. Beattie, S. Gugercin, Interpolatory model reduction of large-scale dynamical systems, Efficient Modeling and Control of Large-Scale Systems, Springer-Verlag, 2010. |
| [BG09] | C. A. Beattie, S. Gugercin, Interpolatory projection methods for structure-preserving model reduction, Systems & Control Letters 58, 2009 |
| [BG12] | C. A. Beattie, S. Gugercin, Realization-independent H2-approximation, Proceedings of the 51st IEEE Conference on Decision and Control, 2012. |
| [BKS11] | P. Benner, M. Köhler, J. Saak, Sparse-Dense Sylvester
Equations in -Model Order
Reduction,
Max Planck Institute Magdeburg Preprint, available
from http://www.mpi-magdeburg.mpg.de/preprints/,
2011. |
| [BEOR14] | A. Buhr, C. Engwer, M. Ohlberger, S. Rave, A Numerically Stable A Posteriori Error Estimator for Reduced Basis Approximations of Elliptic Equations, Proceedings of the 11th World Congress on Computational Mechanics, 2014. |
| [CLVV06] | Y. Chahlaoui, D. Lemonnier, A. Vandendorpe, P. Van Dooren, Second-order balanced truncation, Linear Algebra and its Applications, 2006, 415(2–3), 373-384 |
| [GP05] | M. A. Grepl, A. T. Patera, A Posteriori Error Bounds For Reduced-Basis Approximations Of Parametrized Parabolic Partial Differential Equations, M2AN 39(1), 157-181, 2005. |
| [GAB08] | S. Gugercin, A. C. Antoulas, C. A. Beattie,
model reduction for large-scale
linear dynamical systems,
SIAM Journal on Matrix Analysis and Applications, 30(2),
609-638, 2008. |
| [HDO11] | Haasdonk, B.; Dihlmann, M. & Ohlberger, M., A training set and multiple bases generation approach for parameterized model reduction based on adaptive grids in parameter space, Math. Comput. Model. Dyn. Syst., 2011, 17, 423-442 |
| [HO08] | B. Haasdonk, M. Ohlberger, Reduced basis method for finite volume approximations of parametrized evolution equations, M2AN 42(2), 277-302, 2008. |
| [HLR18] | C. Himpe, T. Leibner, S. Rave, Hierarchical Approximate Proper Orthogonal Decomposition, SIAM J. Sci. Comput. 40, A3267-A3292, 2018. |
| [PK16] | P. Kürschner, Efficient Low-Rank Solution of Large-Scale Matrix Equations, Shaker Verlag Aachen, available from http://pubman.mpdl.mpg.de/pubman/, 2016. |
| [MS96] | D. G. Meyer and S. Srinivasan, Balancing and model reduction for second-order form linear systems, IEEE Trans. Automat. Control, 1996, 41, 1632–1644 |
| [MG91] | D. Mustafa, K. Glover, Controller Reduction by
-Balanced Truncation,
IEEE Transactions on Automatic Control, 36(6), 668-682,
1991. |
| [OJ88] | P. C. Opdenacker, E. A. Jonckheere, A Contraction Mapping Preserving Balanced Reduction Scheme and Its Infinity Norm Error Bounds, IEEE Transactions on Circuits and Systems, 35(2), 184-189, 1988. |
| [RS08] | T. Reis and T. Stykel, Balanced truncation model reduction of second-order systems, Math. Comput. Model. Dyn. Syst., 2008, 14(5), 391-406 |
| [W12] | S. Wyatt, Issues in Interpolatory Model Reduction: Inexact Solves, Second Order Systems and DAEs, PhD thesis, Virginia Tech, 2012 |
| [XZ11] | Y. Xu and T. Zeng, Optimal Model
Reduction for Large Scale MIMO Systems via Tangential
Interpolation,
International Journal of Numerical Analysis and
Modeling, vol. 8, no. 1, pp. 174-188, 2011 |
API Documentation¶
pymor package¶
Subpackages¶
pymor.algorithms package¶
Submodules¶
-
class
pymor.algorithms.adaptivegreedy.AdaptiveSampleSet(parameter_space)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceAn adaptive parameter sample set.
Used by
adaptive_greedy.Methods
AdaptiveSampleSetmap_vertex_to_mu,refine,visualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
AdaptiveSampleSetElementBasicInterfacelogger,logging_disabled,name,uid
-
pymor.algorithms.adaptivegreedy._estimate(mu, rd=None, d=None, reductor=None, error_norm=None)[source]¶ Called by
adaptive_greedy.
-
pymor.algorithms.adaptivegreedy.adaptive_greedy(d, reductor, parameter_space=None, use_estimator=True, error_norm=None, target_error=None, max_extensions=None, validation_mus=0, rho=1.1, gamma=0.2, theta=0.0, extension_params=None, visualize=False, visualize_vertex_size=80, pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Greedy basis generation algorithm with adaptively refined training set.
This method extends pyMOR’s default
greedygreedy basis generation algorithm by adaptive refinement of the parameter training set according to [HDO11] to prevent overfitting of the reduced basis to the training set. This is achieved by estimating the reduction error on an additional validation set of parameters. If the ratio between the estimated errors on the validation set and the validation set is larger thanrho, the training set is refined using standard grid refinement techniques.Parameters
- d
- See
greedy. - reductor
- See
greedy. - parameter_space
- The
ParameterSpacefor which to compute the reduced model. IfNone, the parameter space ofdis used. - use_estimator
- See
greedy. - error_norm
- See
greedy. - target_error
- See
greedy. - max_extensions
- See
greedy. - validation_mus
- One of the following:
- a list of
Parametersto use as validation set, - a positive number indicating the number of random parameters to use as validation set,
- a non-positive number, indicating the negative number of random parameters to use as validation set in addition to the centers of the elements of the adaptive training set.
- a list of
- rho
- Maximum allowed ratio between maximum estimated error on validation set vs. maximum estimated error on training set. If the ratio is larger, the training set is refined.
- gamma
- Weight of the age penalty term in the training set refinement indicators.
- theta
- Ratio of training set elements to select for refinement. (One element is always refined.)
- extension_params
- See
greedy. - visualize
- If
True, visualize the refinement indicators. (Only available for 2 and 3 dimensional parameter spaces.) - visualize_vertex_size
- Size of the vertices in the visualization.
- pool
- See
greedy.
Returns
Dict with the following fields
rd: The reduced Discretizationobtained for the computed basis.extensions: Number of greedy iterations. max_errs: Sequence of maximum errors during the greedy run. max_err_mus: The parameters corresponding to max_errs.max_val_errs: Sequence of maximum errors on the validation set. max_val_err_mus: The parameters corresponding to max_val_errs.refinements: Number of refinements made in each extension step. training_set_sizes: The final size of the training set in each extension step. time: Duration of the algorithm. reduction_data: Reduction data returned by the last reductor call.
-
pymor.algorithms.arnoldi.arnoldi(A, E, b, sigma, trans=False)[source]¶ Rational Arnoldi algorithm.
If
trans == False, using Arnoldi process, computes a real orthonormal basis for the rational Krylov subspace
otherwise, computes the same for

Interpolation points in
sigmaare allowed to repeat (in any order). Then, in the above expression,
is replaced by

Analogously for the
trans == Truecase.Parameters
Returns
- V
- Projection matrix.
Module containing some basic but generic linear algebra algorithms.
-
pymor.algorithms.basic.almost_equal(U, V, product=None, norm=None, rtol=1e-14, atol=1e-14)[source]¶ Compare U and V for almost equality.
The vectors of
UandVare compared in pairs for almost equality. Two vectorsuandvare considered almost equal iff||u - v|| <= atol + ||v|| * rtol.The norm to be used can be specified via the
normorproductparameter.If the length of
Uresp.Vis 1, the single specified vector is compared to all vectors of the other array. Otherwise, the lengths of both indexed arrays have to agree.Parameters
- U, V
VectorArraysto be compared.- product
- If specified, use this inner product
Operatorto compute the norm.productandnormare mutually exclusive. - norm
- If specified, must be a callable which is used to compute the norm
or, alternatively, one of the strings ‘l1’, ‘l2’, ‘sup’, in which case the
respective
VectorArraynorm methods are used.productandnormare mutually exclusive. If neither is specified,norm='l2'is assumed. - rtol
- The relative tolerance.
- atol
- The absolute tolerance.
Defaults
rtol, atol (see
pymor.core.defaults)
-
pymor.algorithms.basic.project_array(U, basis, product=None, orthonormal=True)[source]¶ Orthogonal projection of
VectorArrayonto subspace.Parameters
- U
- The
VectorArrayto project. - basis
VectorArrayof basis vectors for the subspace onto which to project.- product
- Inner product
Operatorw.r.t. which to project. - orthonormal
- If
True, the vectors inbasisare assumed to be orthonormal w.r.t.product.
Returns
The projected
VectorArray.
This module contains algorithms for the empirical interpolation of Operators.
The main work for generating the necessary interpolation data is handled by
the ei_greedy method. The objects returned by this method can be used
to instantiate an EmpiricalInterpolatedOperator.
As a convenience, the interpolate_operators method allows to perform
the empirical interpolation of the Operators of a given discretization with
a single function call.
-
pymor.algorithms.ei.deim(U, modes=None, atol=None, rtol=None, product=None, pod_options={})[source]¶ Generate data for empirical interpolation using DEIM algorithm.
Given a
VectorArrayU, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained inU. The returned objects can be used to instantiate anEmpiricalInterpolatedOperator(withtriangular=False).The collateral basis is determined by the first
podmodes ofU.Parameters
- U
- A
VectorArrayof vectors to interpolate. - modes
- Dimension of the collateral basis i.e. number of POD modes of the vectors in
U. - atol
- Absolute POD tolerance.
- rtol
- Relative POD tolerance.
- product
- Inner product
Operatorused for the POD. - pod_options
- Dictionary of additional options to pass to the
podalgorithm.
Returns
- interpolation_dofs
NumPy arrayof the DOFs at which the vectors are interpolated.- collateral_basis
VectorArraycontaining the generated collateral basis.- data
Dict containing the following fields:
svals: POD singular values.
-
pymor.algorithms.ei.ei_greedy(U, error_norm=None, atol=None, rtol=None, max_interpolation_dofs=None, copy=True, pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Generate data for empirical interpolation using EI-Greedy algorithm.
Given a
VectorArrayU, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained inU. The returned objects can be used to instantiate anEmpiricalInterpolatedOperator(withtriangular=True).The interpolation data is generated by a greedy search algorithm, where in each loop iteration the worst approximated vector in
Uis added to the collateral basis.Parameters
- U
- A
VectorArrayof vectors to interpolate. - error_norm
- Norm w.r.t. which to calculate the interpolation error. If
None, the Euclidean norm is used. - atol
- Stop the greedy search if the largest approximation error is below this threshold.
- rtol
- Stop the greedy search if the largest relative approximation error is below this threshold.
- max_interpolation_dofs
- Stop the greedy search if the number of interpolation DOF (= dimension of the collateral basis) reaches this value.
- copy
- If
False,Uwill be modified during executing of the algorithm. - pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
- interpolation_dofs
NumPy arrayof the DOFs at which the vectors are evaluated.- collateral_basis
VectorArraycontaining the generated collateral basis.- data
Dict containing the following fields:
errors: Sequence of maximum approximation errors during greedy search. triangularity_errors: Sequence of maximum absolute values of interoplation matrix coefficients in the upper triangle (should be near zero).
-
pymor.algorithms.ei.interpolate_operators(d, operator_names, parameter_sample, error_norm=None, product=None, atol=None, rtol=None, max_interpolation_dofs=None, pod_options={}, alg='ei_greedy', pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Empirical operator interpolation using the EI-Greedy/DEIM algorithm.
This is a convenience method to facilitate the use of
ei_greedyordeim. Given aDiscretization, names ofOperators, and a sample ofParameters, first the operators are evaluated on the solution snapshots of the discretization for the provided parameters. These evaluations are then used as input forei_greedy/deim. Finally the resulting interpolation data is used to createEmpiricalInterpolatedOperatorsand a new discretization with the interpolated operators is returned.Note that this implementation creates one common collateral basis for all specified operators, which might not be what you want.
Parameters
- d
- The
DiscretizationwhoseOperatorswill be interpolated. - operator_names
- List of keys in the
operatorsdict of the discretization. The correspondingOperatorswill be interpolated. - parameter_sample
- A list of
Parametersfor which solution snapshots are calculated. - error_norm
- See
ei_greedy. Has no effect ifalg == 'deim'. - product
- Inner product for POD computation in
deim. Has no effect ifalg == 'ei_greedy'. - atol
- See
ei_greedy. - rtol
- See
ei_greedy. - max_interpolation_dofs
- See
ei_greedy. - pod_options
- Further options for
podalgorithm. Has no effect ifalg == 'ei_greedy'. - alg
- Either
ei_greedyordeim. - pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
- ei_d
DiscretizationwithOperatorsgiven byoperator_namesreplaced byEmpiricalInterpolatedOperators.- data
Dict containing the following fields:
dofs: NumPy arrayof the DOFs at which theOperatorshave to be evaluated.basis: VectorArraycontaining the generated collateral basis.In addition,
datacontains the fields of thedatadictreturned byei_greedy/deim.
-
pymor.algorithms.error.reduction_error_analysis(rd, d, reductor, test_mus=10, basis_sizes=0, random_seed=None, estimator=True, condition=False, error_norms=(), error_norm_names=None, estimator_norm_index=0, custom=(), plot=False, plot_custom_logarithmic=True, pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Analyze the model reduction error.
The maximum model reduction error is estimated by solving the reduced
Discretizationfor given randomParameters.Parameters
- rd
- The reduced
Discretization. - d
- The high-dimensional
Discretization. - reductor
- The reductor which has created
rd. - test_mus
- Either a list of
Parametersto compute the errors for, or the number of parameters which are sampled randomly fromparameter_space(if given) orrd.parameter_space. - basis_sizes
- Either a list of reduced basis dimensions to consider, or
the number of dimensions (which are then selected equidistantly,
always including the maximum reduced space dimension).
The dimensions are input for the
dim-Parameter ofreductor.reduce(). - random_seed
- If
test_musis a number, use this value as random seed for drawing theParameters. - estimator
- If
Trueevaluate the error estimator ofrdon the testParameters. - condition
- If
True, compute the condition of the reduced system matrix for the given testParameters(can only be specified ifrdis an instance ofStationaryDiscretizationandrd.operatoris linear). - error_norms
- List of norms in which to compute the model reduction error.
- error_norm_names
- Names of the norms given by
error_norms. IfNone, thenameattributes of the given norms are used. - estimator_norm_index
- When
estimatorisTrueanderror_normsare specified, this is the index of the norm inerror_normsw.r.t. which to compute the effectivity of the estimator. - custom
List of custom functions which are evaluated for each test
Parameterand basis size. The functions must have the signaturedef custom_value(rd, d, reductor, mu, dim): pass
- plot
- If
True, generate a plot of the computed quantities w.r.t. the basis size. - plot_custom_logarithmic
- If
True, use a logarithmic y-axis to plot the computed custom values. - pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
Dict with the following fields
mus: The test Parameterswhich have been considered.basis_sizes: The reduced basis dimensions which have been considered. norms: NumPy arrayof the norms of the high-dimensional solutions w.r.t. all given testParameters, reduced basis dimensions and norms inerror_norms. (Only present whenerror_normshas been specified.)max_norms: Maxima of normsover the given testParameters.max_norm_mus: Parameterscorresponding tomax_norms.errors: NumPy arrayof the norms of the model reduction errors w.r.t. all given testParameters, reduced basis dimensions and norms inerror_norms. (Only present whenerror_normshas been specified.)max_errors: Maxima of errorsover the given testParameters.max_error_mus: Parameterscorresponding tomax_errors.rel_errors: errorsdivided bynorms. (Only present whenerror_normshas been specified.)max_rel_errors: Maxima of rel_errorsover the given testParameters.max_rel_error_mus: Parameterscorresponding tomax_rel_errors.error_norm_names: Names of the given error_norms. (Only present whenerror_normshas been specified.)estimates: NumPy arrayof the model reduction error estimates w.r.t. all given testParametersand reduced basis dimensions. (Only present whenestimatorisTrue.)max_estimate: Maxima of estimatesover the given testParameters.max_estimate_mus: Parameterscorresponding tomax_estimates.effectivities: errorsdivided byestimates. (Only present whenestimatorisTrueanderror_normshas been specified.)min_effectivities: Minima of effectivitiesover the given testParameters.min_effectivity_mus: Parameterscorresponding tomin_effectivities.max_effectivities: Maxima of effectivitiesover the given testParameters.max_effectivity_mus: Parameterscorresponding tomax_effectivities.errors: NumPy arrayof the reduced system matrix conditions w.r.t. all given testParametersand reduced basis dimensions. (Only present whenconditionsisTrue.)max_conditions: Maxima of conditionsover the given testParameters.max_condition_mus: Parameterscorresponding tomax_conditions.custom_values: NumPy arrayof custom function evaluations w.r.t. all given testParameters, reduced basis dimensions and functions incustom. (Only present whencustomhas been specified.)max_custom_values: Maxima of custom_valuesover the given testParameters.max_custom_values_mus: Parameterscorresponding tomax_custom_values.time: Time (in seconds) needed for the error analysis. summary: String containing a summary of all computed quantities for the largest (last) considered basis size. figure: The figure containing the generated plots. (Only present when plotisTrue.)
This module contains some iterative linear solvers which only use the Operator interface
-
pymor.algorithms.genericsolvers.apply_inverse(op, rhs, options=None, least_squares=False, check_finite=True, default_solver='generic_lgmres', default_least_squares_solver='generic_least_squares_lsmr')[source]¶ Solve linear equation system.
Applies the inverse of
opto the vectors inrhsusing a generic iterative solver.Parameters
- op
- The linear, non-parametric
Operatorto invert. - rhs
VectorArrayof right-hand sides for the equation system.- options
- The
solver_optionsto use (seesolver_options). - least_squares
- If
True, return least squares solution. - check_finite
- Test if solution only contains finite values.
- default_solver
- Default solver to use (generic_lgmres, generic_least_squares_lsmr, generic_least_squares_lsqr).
- default_least_squares_solver
- Default solver to use for least squares problems (generic_least_squares_lsmr, generic_least_squares_lsqr).
Returns
VectorArrayof the solution vectors.Defaults
check_finite, default_solver, default_least_squares_solver (see
pymor.core.defaults)
-
pymor.algorithms.genericsolvers.lgmres(A, b, x0=None, tol=1e-05, maxiter=1000, M=None, callback=None, inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True)[source]¶
-
pymor.algorithms.genericsolvers.lsmr(A, b, damp=0.0, atol=1e-06, btol=1e-06, conlim=100000000.0, maxiter=None, show=False)[source]¶
-
pymor.algorithms.genericsolvers.lsqr(A, b, damp=0.0, atol=1e-08, btol=1e-08, conlim=100000000.0, iter_lim=None, show=False)[source]¶
-
pymor.algorithms.genericsolvers.solver_options(lgmres_tol=1e-05, lgmres_maxiter=1000, lgmres_inner_m=39, lgmres_outer_k=3, least_squares_lsmr_damp=0.0, least_squares_lsmr_atol=1e-06, least_squares_lsmr_btol=1e-06, least_squares_lsmr_conlim=100000000.0, least_squares_lsmr_maxiter=None, least_squares_lsmr_show=False, least_squares_lsqr_damp=0.0, least_squares_lsqr_atol=1e-06, least_squares_lsqr_btol=1e-06, least_squares_lsqr_conlim=100000000.0, least_squares_lsqr_iter_lim=None, least_squares_lsqr_show=False)[source]¶ Returns available solvers with default
solver_options.Parameters
- lgmres_tol
- See
scipy.sparse.linalg.lgmres. - lgmres_maxiter
- See
scipy.sparse.linalg.lgmres. - lgmres_inner_m
- See
scipy.sparse.linalg.lgmres. - lgmres_outer_k
- See
scipy.sparse.linalg.lgmres. - least_squares_lsmr_damp
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_atol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_btol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_conlim
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_maxiter
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_show
- See
scipy.sparse.linalg.lsmr. - least_squares_lsqr_damp
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_atol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_btol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_conlim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_iter_lim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_show
- See
scipy.sparse.linalg.lsqr.
Returns
A dict of available solvers with default
solver_options.Defaults
lgmres_tol, lgmres_maxiter, lgmres_inner_m, lgmres_outer_k, least_squares_lsmr_damp, least_squares_lsmr_atol, least_squares_lsmr_btol, least_squares_lsmr_conlim, least_squares_lsmr_maxiter, least_squares_lsmr_show, least_squares_lsqr_atol, least_squares_lsqr_btol, least_squares_lsqr_conlim, least_squares_lsqr_iter_lim, least_squares_lsqr_show (see
pymor.core.defaults)
-
pymor.algorithms.gram_schmidt.gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]¶ Orthonormalize a
VectorArrayusing the stabilized Gram-Schmidt algorithm.Parameters
- A
- The
VectorArraywhich is to be orthonormalized. - product
- The inner product
Operatorw.r.t. which to orthonormalize. IfNone, the Euclidean product is used. - atol
- Vectors of norm smaller than
atolare removed from the array. - rtol
- Relative tolerance used to detect linear dependent vectors (which are then removed from the array).
- offset
- Assume that the first
offsetvectors are already orthonormal and start the algorithm at theoffset + 1-th vector. - reiterate
- If
True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector. - reiteration_threshold
- If
reiterateisTrue, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value. - check
- If
True, check if the resultingVectorArrayis really orthonormal. - check_tol
- Tolerance for the check.
- copy
- If
True, create a copy ofAinstead of modifyingAin-place.
Returns
The orthonormalized
VectorArray.Defaults
atol, rtol, reiterate, reiteration_threshold, check, check_tol (see
pymor.core.defaults)
-
pymor.algorithms.gram_schmidt.gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]¶ Biorthonormalize a pair of
VectorArraysusing the biorthonormal Gram-Schmidt process.See Algorithm 1 in [BKS11].
Parameters
- V, W
- The
VectorArrayswhich are to be biorthonormalized. - product
- The inner product
Operatorw.r.t. which to biorthonormalize. IfNone, the Euclidean product is used. - reiterate
- If
True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector. - reiteration_threshold
- If
reiterateisTrue, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value. - check
- If
True, check if the resultingVectorArrayis really orthonormal. - check_tol
- Tolerance for the check.
- copy
- If
True, create a copy ofVandWinstead of modifyingVandWin-place.
Returns
The biorthonormalized
VectorArrays.
-
pymor.algorithms.greedy.greedy(d, reductor, samples, use_estimator=True, error_norm=None, atol=None, rtol=None, max_extensions=None, extension_params=None, pool=None)[source]¶ Greedy basis generation algorithm.
This algorithm generates a reduced basis by iteratively adding the worst approximated solution snapshot for a given training set to the reduced basis. The approximation error is computed either by directly comparing the reduced solution to the detailed solution or by using an error estimator (
use_estimator == True). The reduction and basis extension steps are performed by calling the methods provided by thereductorandextension_algorithmarguments.Parameters
- d
- The
Discretizationto reduce. - reductor
- Reductor for reducing the given
Discretization. This has to be an object with areducemethod, such thatreductor.reduce()yields the reduced discretization, and anexted_basismethod, such thatreductor.extend_basis(U, copy_U=False, **extension_params)extends the current reduced basis by the vectors contained inU. For an example seeCoerciveRBReductor. - samples
- The set of
Parametersamples on which to perform the greedy search. - use_estimator
- If
True, userd.estimate()to estimate the errors on the sample set. Otherwised.solve()is called to compute the exact model reduction error. - error_norm
- If
use_estimator == False, use this function to calculate the norm of the error. IfNone, the Euclidean norm is used. - atol
- If not
None, stop the algorithm if the maximum (estimated) error on the sample set drops below this value. - rtol
- If not
None, stop the algorithm if the maximum (estimated) relative error on the sample set drops below this value. - max_extensions
- If not
None, stop the algorithm aftermax_extensionsextension steps. - extension_params
dictof parameters passed to thereductor.extend_basismethod.- pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
Dict with the following fields
rd: The reduced Discretizationobtained for the computed basis.max_errs: Sequence of maximum errors during the greedy run. max_err_mus: The parameters corresponding to max_errs.extensions: Number of performed basis extensions. time: Total runtime of the algorithm.
-
class
pymor.algorithms.hapod.DistHAPODTree(slices)[source]¶ Bases:
pymor.algorithms.hapod.TreeMethods
DistHAPODTreechildrenTreeis_leafBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
Treedepth,rootBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.algorithms.hapod.FakeExecutor[source]¶ Bases:
objectMethods
FakeExecutorsubmit
-
class
pymor.algorithms.hapod.IncHAPODTree(steps)[source]¶ Bases:
pymor.algorithms.hapod.TreeMethods
IncHAPODTreechildrenTreeis_leafBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
Treedepth,rootBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.algorithms.hapod.LifoExecutor(executor, max_workers=None)[source]¶ Bases:
objectMethods
LifoExecutordone_callback,run_task,submit
-
class
pymor.algorithms.hapod.Tree[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceA rooted tree.
Methods
Treechildren,is_leafBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
Treedepth,rootBasicInterfacelogger,logging_disabled,name,uid
-
pymor.algorithms.hapod.dist_hapod(num_slices, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]¶ Distributed Hierarchical Approximate POD.
This computes the distributed HAPOD from [HLR18].
Parameters
- num_slices
- The number of snapshot vector slices.
- snapshots
- A mapping
snapshots(slice)returning for each slice number the associated snapshot vectors. - eps
- Desired l2-mean approximation error.
- omega
- Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
- Inner product
Operatorw.r.t. which to compute the POD. - executor
- If not
None, aconcurrent.futures.Executorobject to use for parallelization. - eval_snapshots_in_executor
- If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
- The computed POD modes.
- svals
- The associated singular values.
- snap_count
- The total number of input snapshot vectors.
-
pymor.algorithms.hapod.dist_vectorarray_hapod(num_slices, U, eps, omega, product=None, executor=None)[source]¶ Distributed Hierarchical Approximate POD.
This computes the distributed HAPOD from [HLR18] of a given
VectorArray.Parameters
- num_slices
- The number of snapshot vector slices.
- U
- The
VectorArrayof which to compute the HAPOD. - eps
- Desired l2-mean approximation error.
- omega
- Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
- Inner product
Operatorw.r.t. which to compute the POD. - executor
- If not
None, aconcurrent.futures.Executorobject to use for parallelization.
Returns
- modes
- The computed POD modes.
- svals
- The associated singular values.
- snap_count
- The total number of input snapshot vectors.
-
pymor.algorithms.hapod.hapod(tree, snapshots, local_eps, product=None, pod_method=<function default_pod_method>, executor=None, eval_snapshots_in_executor=False)[source]¶ Compute the Hierarchical Approximate POD.
This is an implementation of the HAPOD algorithm from [HLR18].
Parameters
- tree
- A
Treedefining the worker topology. - snapshots
- A mapping
snapshots(node)returning for each leaf node the associated snapshot vectors. - local_eps
- A mapping
local_eps(node, snap_count, num_vecs)assigning to each tree nodenodean l2 truncation error tolerance for the local pod based on the number of input vectorsnum_vecsand the total number of snapshot vectors below the given nodesnap_count. - product
- Inner product
Operatorw.r.t. which to compute the POD. - pod_method
- A function
pod_method(U, eps, root_node, product)for computing the POD of theVectorArrayUw.r.t. the given inner productproductand the l2 error toleranceeps.root_nodeis set toTruewhen the POD is computed at the root of the tree. - executor
- If not
None, aconcurrent.futures.Executorobject to use for parallelization. - eval_snapshots_in_executor
- If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
- The computed POD modes.
- svals
- The associated singular values.
- snap_count
- The total number of input snapshot vectors.
-
pymor.algorithms.hapod.inc_hapod(steps, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]¶ Incremental Hierarchical Approximate POD.
This computes the incremental HAPOD from [HLR18].
Parameters
- steps
- The number of incremental POD updates.
- snapshots
- A mapping
snapshots(step)returning for each incremental POD step the associated snapshot vectors. - eps
- Desired l2-mean approximation error.
- omega
- Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
- Inner product
Operatorw.r.t. which to compute the POD. - executor
- If not
None, aconcurrent.futures.Executorobject to use for parallelization. - eval_snapshots_in_executor
- If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
- The computed POD modes.
- svals
- The associated singular values.
- snap_count
- The total number of input snapshot vectors.
-
pymor.algorithms.hapod.inc_vectorarray_hapod(steps, U, eps, omega, product=None, executor=None)[source]¶ Incremental Hierarchical Approximate POD.
This computes the incremental HAPOD from [HLR18] for a given
VectorArray.Parameters
- steps
- The number of incremental POD updates.
- U
- The
VectorArrayof which to compute the HAPOD. - eps
- Desired l2-mean approximation error.
- omega
- Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
- Inner product
Operatorw.r.t. which to compute the POD. - executor
- If not
None, aconcurrent.futures.Executorobject to use for parallelization. - eval_snapshots_in_executor
- If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
- The computed POD modes.
- svals
- The associated singular values.
- snap_count
- The total number of input snapshot vectors.
-
class
pymor.algorithms.image.CollectOperatorRangeRules(source, image, extends)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theestimate_imagealgorithm.Methods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
CollectOperatorRangeRulesaction_apply_operator,action_Concatenation,action_EmpiricalInterpolatedOperator,action_recurse,rulesBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.algorithms.image.CollectVectorRangeRules(image)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theestimate_imagealgorithm.Methods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
CollectVectorRangeRulesaction_as_range_array,action_Concatenation,action_recurse,action_VectorArray,rulesBasicInterfacelogger,logging_disabled,name,uid
-
pymor.algorithms.image.estimate_image(operators=(), vectors=(), domain=None, extends=False, orthonormalize=True, product=None, riesz_representatives=False)[source]¶ Estimate the image of given
Operatorsfor all mu.Let
operatorsbe a list ofOperatorswith common source and range, and letvectorsbe a list ofVectorArraysor vector-likeOperatorsin the range of these operators. Given aVectorArraydomainof vectors in the source of the operators, this algorithms determines aVectorArrayimageof range vectors such that the linear span ofimagecontains:op.apply(U, mu=mu)for all operatorsopinoperators, for all possibleParametersmuand for allVectorArraysUcontained in the linear span ofdomain,Ufor allVectorArraysinvectors,v.as_range_array(mu)for allOperatorsinvectorsand all possibleParametersmu.
The algorithm will try to choose
imageas small as possible. However, no optimality is guaranteed. The image estimation algorithm is specified byCollectOperatorRangeRulesandCollectVectorRangeRules.Parameters
- operators
- See above.
- vectors
- See above.
- domain
- See above. If
None, an emptydomainVectorArrayis assumed. - extends
- For some operators, e.g.
EmpiricalInterpolatedOperator, as well as for all elements ofvectors,imageis estimated independently from the choice ofdomain. IfextendsisTrue, such operators are ignored. (This is useful in case these vectors have already been obtained by earlier calls to this function.) - orthonormalize
- Compute an orthonormal basis for the linear span of
imageusing thegram_schmidtalgorithm. - product
- Inner product
Operatorw.r.t. which to orthonormalize. - riesz_representatives
- If
True, compute Riesz representatives of the vectors inimagebefore orthonormalizing (useful for dual norm computation when the range of theoperatorsis a dual space).
Returns
The
VectorArrayimage.Raises
- ImageCollectionError
- Is raised when for a given
Operatorno image estimate is possible.
-
pymor.algorithms.image.estimate_image_hierarchical(operators=(), vectors=(), domain=None, extends=None, orthonormalize=True, product=None, riesz_representatives=False)[source]¶ Estimate the image of given
Operatorsfor all mu.This is an extended version of
estimate_image, which callsestimate_imageindividually for each vector ofdomain.As a result, the vectors in the returned
imageVectorArraywill be ordered by thedomainvector they correspond to (starting with vectors which correspond to the elements ofvectorsand toOperatorsfor which the image is estimated independently fromdomain).This function also returns an
image_dimslist, such that the firstimage_dims[i+1]vectors ofimagecorrespond to the firstivectors ofdomain(the firstimage_dims[0]vectors correspond tovectorsand toOperatorswith fixed image estimate).Parameters
- operators
- See
estimate_image. - vectors
- See
estimate_image. - domain
- See
estimate_image. - extends
- When additional vectors have been appended to the
domainVectorArrayafterestimate_image_hierarchicalhas been called, andestimate_image_hierarchicalshall be called again for the extendeddomainarray,extendscan be set to(image, image_dims), whereimage,image_dimsare the return values of the lastestimate_image_hierarchicalcall. The olddomainvectors will then be skipped during computation andimage,image_dimswill be modified in-place. - orthonormalize
- See
estimate_image. - product
- See
estimate_image. - riesz_representatives
- See
estimate_image.
Returns
- image
- See above.
- image_dims
- See above.
Raises
- ImageCollectionError
- Is raised when for a given
Operatorno image estimate is possible.
-
pymor.algorithms.lradi.lyap_lrcf_solver_options(lradi_tol=1e-10, lradi_maxiter=500, lradi_shifts='projection_shifts', projection_shifts_z_columns=1, projection_shifts_init_maxiter=20, projection_shifts_init_seed=None, projection_shifts_implicit_subspace=True)[source]¶ Returns available Lyapunov equation solvers with default solver options.
Parameters
- lradi_tol
- See
solve_lyap_lrcf. - lradi_maxiter
- See
solve_lyap_lrcf. - lradi_shifts
- See
solve_lyap_lrcf. - projection_shifts_z_columns
- See
projection_shifts. - projection_shifts_init_maxiter
- See
projection_shifts_init. - projection_shifts_init_seed
- See
projection_shifts_init. - projection_shifts_implicit_subspace
- See
projection_shifts.
Returns
A dict of available solvers with default solver options.
Defaults
lradi_tol, lradi_maxiter, lradi_shifts, projection_shifts_z_columns, projection_shifts_init_maxiter, projection_shifts_init_seed, projection_shifts_implicit_subspace (see
pymor.core.defaults)
-
pymor.algorithms.lradi.projection_shifts(A, E, Z, W, prev_shifts, shift_options)[source]¶ Find further shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.
See [PK16], pp. 92-95.
Parameters
- A
- The
OperatorA from the corresponding Lyapunov equation. - E
- The
OperatorE from the corresponding Lyapunov equation. - Z
- A
VectorArrayrepresenting the currently computed low-rank solution factor. - W
- A
VectorArrayrepresenting the currently computed low-rank residual factor. - prev_shifts
- A
NumPy arraycontaining the set of all previously used shift parameters. - shift_options
- The shift options to use (see
lyap_lrcf_solver_options).
Returns
- shifts
- A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lradi.projection_shifts_init(A, E, B, shift_options)[source]¶ Find starting shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.
See [PK16], pp. 92-95.
Parameters
- A
- The
OperatorA from the corresponding Lyapunov equation. - E
- The
OperatorE from the corresponding Lyapunov equation. - B
- The
VectorArrayB from the corresponding Lyapunov equation. - shift_options
- The shift options to use (see
lyap_lrcf_solver_options).
Returns
- shifts
- A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lradi.solve_lyap_lrcf(A, E, B, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a Lyapunov equation.
See
pymor.algorithms.lyapunov.solve_lyap_lrcffor a general description.This function uses the low-rank ADI iteration as described in Algorithm 4.3 in [PK16]. We assume in
projection_shifts_initforA.source.from_numpyto be implemented if projecting (A, E) with B does not give stable eigenvalues.Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - trans
- Whether the first
Operatorin the Lyapunov equation is transposed. - options
- The solver options to use (see
lyap_lrcf_solver_options).
Returns
- Z
- Low-rank Cholesky factor of the Lyapunov equation solution,
VectorArrayfromA.source.
-
pymor.algorithms.lyapunov._chol(A)[source]¶ Cholesky decomposition.
This implementation uses SVD to compute the Cholesky factor (can be used for singular matrices).
Parameters
- A
- Symmetric positive semidefinite matrix as a
NumPy array.
Returns
- L
- Cholesky factor of A (in the sense that L * L^T approximates A).
-
pymor.algorithms.lyapunov.mat_eqn_sparse_min_size(value=1000)[source]¶ Returns minimal size for which a sparse solver will be used by default.
Defaults
value (see
pymor.core.defaults)
-
pymor.algorithms.lyapunov.solve_lyap_dense(A, E, B, trans=False, options=None, default_solver_backend='scipy')[source]¶ Compute the solution of a Lyapunov equation.
Returns the solution
of a (generalized) continuous-time
algebraic Lyapunov equation:if trans is
Falseand E isNone:
if trans is
Falseand E is anOperator:
if trans is
Trueand E isNone:
if trans is
Trueand E is anOperator:
We assume A and E are real
NumPy arrays, E is invertible, and that no two eigenvalues of (A, E) sum to zero (i.e., there exists a unique solution X).If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
pymess(seepymor.bindings.pymess.solve_lyap_dense)slycot(seepymor.bindings.slycot.solve_lyap_dense)scipy(seepymor.bindings.scipy.solve_lyap_dense)
Parameters
- A
- The operator A as a 2D
NumPy array. - E
- The operator E as a 2D
NumPy arrayorNone. - B
- The operator B as a 2D
NumPy array. - trans
- Whether the first operator in the Lyapunov equation is transposed.
- options
The solver options to use. See:
pymor.bindings.scipy.lyap_dense_solver_options,pymor.bindings.slycot.lyap_dense_solver_options,pymor.bindings.pymess.lyap_dense_solver_options.
- default_solver_backend
- Default solver backend to use (pymess, slycot, scipy).
Returns
- X
- Lyapunov equation solution as a
NumPy array.
Defaults
default_solver_backend (see
pymor.core.defaults)
-
pymor.algorithms.lyapunov.solve_lyap_lrcf(A, E, B, trans=False, options=None, default_sparse_solver_backend='lradi', default_dense_solver_backend='scipy')[source]¶ Compute an approximate low-rank solution of a Lyapunov equation.
Returns a low-rank Cholesky factor
such that
approximates the solution
of a (generalized)
continuous-time algebraic Lyapunov equation:if trans is
Falseand E isNone:
if trans is
Falseand E is anOperator:
if trans is
Trueand E isNone:
if trans is
Trueand E is anOperator:
We assume A and E are real
Operators, E is invertible, and all the eigenvalues of (A, E) all lie in the open left half-plane. Operator B needs to be given as aVectorArrayfromA.source, and for large-scale problems, we assumelen(B)is small.If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
- for sparse problems (minimum size specified by
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_lyap_lrcf),lradi(seepymor.algorithms.lradi.solve_lyap_lrcf),
- for dense problems (smaller than
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_lyap_lrcf),slycot(seepymor.bindings.slycot.solve_lyap_lrcf),scipy(seepymor.bindings.scipy.solve_lyap_lrcf).
Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - trans
- Whether the first
Operatorin the Lyapunov equation is transposed. - options
The solver options to use. See:
pymor.algorithms.lradi.lyap_lrcf_solver_options,pymor.bindings.scipy.lyap_lrcf_solver_options,pymor.bindings.slycot.lyap_lrcf_solver_options,pymor.bindings.pymess.lyap_lrcf_solver_options.
- default_sparse_solver_backend
- Default sparse solver backend to use (pymess, lradi).
- default_dense_solver_backend
- Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
- Low-rank Cholesky factor of the Lyapunov equation solution,
VectorArrayfromA.source.
Defaults
default_sparse_solver_backend, default_dense_solver_backend (see
pymor.core.defaults)
-
pymor.algorithms.newton.newton(operator, rhs, initial_guess=None, mu=None, error_norm=None, least_squares=False, miniter=0, maxiter=100, rtol=-1.0, atol=-1.0, stagnation_window=3, stagnation_threshold=0.9, return_stages=False, return_residuals=False)[source]¶ Basic Newton algorithm.
This method solves the nonlinear equation
A(U, mu) = V
for
Uusing the Newton method.Parameters
- operator
- The
OperatorA.Amust implement thejacobianinterface method. - rhs
VectorArrayof length 1 containing the vectorV.- initial_guess
- If not
None, aVectorArrayof length 1 containing an initial guess for the solutionU. - mu
- The
Parameterfor which to solve the equation. - error_norm
- The norm with which the norm of the residual is computed. If
None, the Euclidean norm is used. - least_squares
- If
True, use a least squares linear solver (e.g. for residual minimization). - miniter
- Minimum amount of iterations to perform.
- maxiter
- Fail if the iteration count reaches this value without converging.
- rtol
- Finish when the residual norm has been reduced by this factor relative to the norm of the initial residual.
- atol
- Finish when the residual norm is below this threshold.
- stagnation_window
- Finish when the residual norm has not been reduced by a factor of
stagnation_thresholdduring the laststagnation_windowiterations. - stagnation_threshold
- See
stagnation_window. - return_stages
- If
True, return aVectorArrayof the intermediate approximations ofUafter each iteration. - return_residuals
- If
True, return aVectorArrayof all residual vectors which have been computed during the Newton iterations.
Returns
- U
VectorArrayof length 1 containing the computed solution- data
Dict containing the following fields:
error_sequence: NumPy arraycontaining the residual norms after each iteration.stages: See return_stages.residuals: See return_residuals.
Raises
- NewtonError
- Raised if the Netwon algorithm failed to converge.
Defaults
miniter, maxiter, rtol, atol, stagnation_window, stagnation_threshold (see
pymor.core.defaults)
-
pymor.algorithms.pod.pod(A, modes=None, product=None, rtol=4e-08, atol=0.0, l2_err=0.0, symmetrize=False, orthonormalize=True, check=True, check_tol=1e-10)[source]¶ Proper orthogonal decomposition of
A.Viewing the
VectorArrayAas aA.dimxlen(A)matrix, the return value of this method is theVectorArrayof left-singular vectors of the singular value decomposition ofA, where the inner product on R^(dim(A)) is given byproductand the inner product on R^(len(A)) is the Euclidean inner product.Parameters
- A
- The
VectorArrayfor which the POD is to be computed. - modes
- If not
None, only the firstmodesPOD modes (singular vectors) are returned. - product
- Inner product
Operatorw.r.t. which the POD is computed. - rtol
- Singular values smaller than this value multiplied by the largest singular value are ignored.
- atol
- Singular values smaller than this value are ignored.
- l2_err
Do not return more modes than needed to bound the l2-approximation error by this value. I.e. the number of returned modes is at most
argmin_N { sum_{n=N+1}^{infty} s_n^2 <= l2_err^2 }
where
s_ndenotes the n-th singular value.- symmetrize
- If
True, symmetrize the Gramian again before proceeding. - orthonormalize
- If
True, orthonormalize the computed POD modes again using thegram_schmidtalgorithm. - check
- If
True, check the computed POD modes for orthonormality. - check_tol
- Tolerance for the orthonormality check.
Returns
- POD
VectorArrayof POD modes.- SVALS
- Sequence of singular values.
Defaults
rtol, atol, l2_err, symmetrize, orthonormalize, check, check_tol (see
pymor.core.defaults)
-
class
pymor.algorithms.preassemble.PreAssembleRules[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
PreAssembleRulesaction_AdjointOperator,action_assemble,action_identity,action_recurse,action_recurse_and_assemble,rulesBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.algorithms.projection.ProjectRules(range_basis, source_basis, product)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theprojectalgorithm.Methods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ProjectRulesaction_AdjointOperator,action_AffineOperator,action_apply_basis,action_Concatenation,action_ConstantOperator,action_EmpiricalInterpolatedOperator,action_generic_projection,action_LincombOperator,action_SelectionOperator,action_ZeroOperator,rulesBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.algorithms.projection.ProjectToSubbasisRules(dim_range, dim_source)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theproject_to_subbasisalgorithm.Methods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ProjectToSubbasisRulesaction_ConstantOperator,action_IdentityOperator,action_NumpyMatrixOperator,action_ProjectedEmpiciralInterpolatedOperator,action_ProjectedOperator,action_recurse,rulesBasicInterfacelogger,logging_disabled,name,uid
-
pymor.algorithms.projection.project(op, range_basis, source_basis, product=None)[source]¶ Petrov-Galerkin projection of a given
Operator.Given an inner product
( ⋅, ⋅), source vectorsb_1, ..., b_Nand range vectorsc_1, ..., c_M, the projectionop_projofopis defined by[ op_proj(e_j) ]_i = ( c_i, op(b_j) )
for all i,j, where
e_jdenotes the j-th canonical basis vector of R^N.In particular, if the
c_iare orthonormal w.r.t. the given product, thenop_projis the coordinate representation w.r.t. theb_i/c_ibases of the restriction ofoptospan(b_i)concatenated with the orthogonal projection ontospan(c_i).From another point of view, if
opis viewed as a bilinear form (seeapply2) and( ⋅, ⋅ )is the Euclidean inner product, thenop_projrepresents the matrix of the bilinear form restricted tospan(b_i) / span(c_i)(w.r.t. theb_i/c_ibases).How the projection is realized will depend on the given
Operator. While a projectedNumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general. The exact algorithm is specified inProjectRules.Parameters
- range_basis
- The vectors
c_1, ..., c_Mas aVectorArray. IfNone, no projection in the range space is performed. - source_basis
- The vectors
b_1, ..., b_Nas aVectorArrayorNone. IfNone, no restriction of the source space is performed. - product
- An
Operatorrepresenting the inner product. IfNone, the Euclidean inner product is chosen.
Returns
The projected
Operatorop_proj.
-
pymor.algorithms.projection.project_to_subbasis(op, dim_range=None, dim_source=None)[source]¶ Project already projected
Operatorto a subbasis.The purpose of this method is to further project an operator that has been obtained through
projectto subbases of the original projection bases, i.e.project_to_subbasis(project(op, r_basis, s_basis, prod), dim_range, dim_source)
should be the same as
project(op, r_basis[:dim_range], s_basis[:dim_source], prod)
For a
NumpyMatrixOperatorthis amounts to extracting the upper-left (dim_range, dim_source) corner of its matrix.The subbasis projection algorithm is specified in
ProjectToSubbasisRules.Parameters
- dim_range
- Dimension of the range subbasis.
- dim_source
- Dimension of the source subbasis.
Returns
The projected
Operator.
-
pymor.algorithms.riccati.solve_pos_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None, default_dense_solver_backend='scipy')[source]¶ Compute an approximate low-rank solution of a positive Riccati equation.
Returns a low-rank Cholesky factor
such that
approximates the solution
of a (generalized) positive
continuous-time algebraic Riccati equation:if trans is
False
if trans is
True
If E is None, it is taken to be identity, and similarly for R. If S is None, it is taken to be zero.
If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
pymess(seepymor.bindings.pymess.solve_pos_ricc_lrcf),slycot(seepymor.bindings.slycot.solve_pos_ricc_lrcf),scipy(seepymor.bindings.scipy.solve_pos_ricc_lrcf).
Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - C
- The operator C as a
VectorArrayfromA.source. - R
- The operator R as a 2D
NumPy arrayorNone. - S
- The operator S as a
VectorArrayfromA.sourceorNone. - trans
- Whether the first
Operatorin the positive Riccati equation is transposed. - options
The solver options to use. See:
pymor.bindings.scipy.pos_ricc_lrcf_solver_options,pymor.bindings.slycot.pos_ricc_lrcf_solver_options,pymor.bindings.pymess.pos_ricc_lrcf_solver_options.
- default_dense_solver_backend
- Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
- Low-rank Cholesky factor of the positive Riccati equation
solution,
VectorArrayfromA.source.
Defaults
default_dense_solver_backend (see
pymor.core.defaults)
-
pymor.algorithms.riccati.solve_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None, default_sparse_solver_backend='pymess', default_dense_solver_backend='scipy')[source]¶ Compute an approximate low-rank solution of a Riccati equation.
Returns a low-rank Cholesky factor
such that
approximates the solution
of a (generalized)
continuous-time algebraic Riccati equation:if trans is
False
if trans is
True
If E is None, it is taken to be identity, and similarly for R. If S is None, it is taken to be zero.
We assume:
- A and E are real
Operators, - B, C and S are real
VectorArraysfromA.source, - R is a real
NumPy array, - (E, A, B, C) is stabilizable and detectable,
- R is symmetric positive definite, and
(
) is
positive semi-definite trans is False(True).
For large-scale problems, we additionally assume that
len(B)andlen(C)are small.If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
- for sparse problems (minimum size specified by
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_ricc_lrcf),
- for dense problems (smaller than
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_ricc_lrcf),slycot(seepymor.bindings.slycot.solve_ricc_lrcf),scipy(seepymor.bindings.scipy.solve_ricc_lrcf).
Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - C
- The operator C as a
VectorArrayfromA.source. - R
- The operator R as a 2D
NumPy arrayorNone. - S
- The operator S as a
VectorArrayfromA.sourceorNone. - trans
- Whether the first
Operatorin the Riccati equation is transposed. - options
The solver options to use. See:
pymor.bindings.scipy.ricc_lrcf_solver_options,pymor.bindings.slycot.ricc_lrcf_solver_options,pymor.bindings.pymess.ricc_lrcf_solver_options.
- default_sparse_solver_backend
- Default sparse solver backend to use (pymess).
- default_dense_solver_backend
- Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
- Low-rank Cholesky factor of the Riccati equation solution,
VectorArrayfromA.source.
Defaults
default_sparse_solver_backend, default_dense_solver_backend (see
pymor.core.defaults)
-
class
pymor.algorithms.rules.RuleTable(use_caching=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceDefine algorithm by a table of match conditions and corresponding actions.
RuleTablemanages a table ofrules, stored in therulesattributes, which can beappliedto given objects.A new table is created by subclassing
RuleTableand defining new methods which are decorated withmatch_class,match_genericor anotherrulesubclass. The order of the method definitions determines the order in which the definedrulesare applied.Parameters
- use_caching
- If
True, cache results ofapply.
Methods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
RuleTablerulesBasicInterfacelogger,logging_disabled,name,uid-
apply(obj)[source]¶ Sequentially apply rules to given object.
This method iterates over all rules of the given
RuleTable. For eachrule, it is checked if itmatchesthe given object. IfFalse, the nextrulein the table is considered. IfTruethe correspondingactionis executed withobjas parameter. If execution ofactionraisesRuleNotMatchingError, the rule is considered as not matching, and execution continues with evaluation of the next rule. Otherwise, execution is stopped and the return value ofrule.actionis returned to the caller.If no
rulematches, aNoMatchingRuleErroris raised.Parameters
- obj
- The object to apply the
RuleTableto.
Returns
Return value of the action of the first matching
rulein the table.Raises
- NoMatchingRuleError
- No
rulecould be applied to the given object.
-
apply_children(obj, children=None)[source]¶ Apply rules to all children of the given object.
This method calls
applyto each child of the given object. The children of the object are either provided by thechildrenparameter or automatically inferred by theget_childrenmethod.Parameters
- obj
- The object to apply the
RuleTableto. - children
Noneor a list of attribute names defining the children to consider.
Returns
Result of : meth:
applyfor all given children.
-
classmethod
get_children(obj)[source]¶ Determine children of given object.
This method returns a list of the names of all attributes
a, for which one of the folling is true:
-
replace_children(obj, children=None)[source]¶ Replace children of object according to rule table.
Same as
apply_children, but additionally callsobj.with_to replace the children ofobjwith the result of the correspondingapplycall.
-
class
pymor.algorithms.rules.RuleTableMeta(name, bases, namespace)[source]¶ Bases:
pymor.core.interfaces.UberMetaMeta class for
RuleTable.Methods
ABCMetaregister,__instancecheck__,__subclasscheck__typemro,__dir__,__prepare__,__sizeof__,__subclasses__-
static
__new__(cls, name, parents, dct)[source]¶ I copy docstrings from base class methods to deriving classes.
Copying of docstrings is disabled when the
PYMOR_WITH_SPHINXenvironment variable is set to1.
-
__str__()¶ Return repr(self).
-
static
-
class
pymor.algorithms.rules.match_class(*classes)[source]¶ Bases:
pymor.algorithms.rules.rulerulethat matches when obj is instance of one of the given classes.Methods
match_classmatchesAttributes
match_classcondition_typeruleaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.match_generic(condition, condition_description=None)[source]¶ Bases:
pymor.algorithms.rules.rulerulewith matching condition given by an arbitrary function.Parameters
- condition
- Function of one argument which checks if given object matches condition.
- condition_description
- Optional string describing the condition implemented by
condition.
Methods
match_genericmatchesAttributes
match_genericcondition_typeruleaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.rule[source]¶ Bases:
objectDecorator to make a method a rule in a given
RuleTable.The decorated function will become the
actionto perform in case the rulematches. Matching conditions are specified by subclassing and overriding thematchesmethod.-
action¶ Method to call in case the rule matches.
-
-
pymor.algorithms.sylvester.solve_sylv_schur(A, Ar, E=None, Er=None, B=None, Br=None, C=None, Cr=None)[source]¶ Solve Sylvester equation by Schur decomposition.
Solves Sylvester equation

or

or both using (generalized) Schur decomposition (Algorithms 3 and 4 in [BKS11]), if the necessary parameters are given.
Parameters
- A
- Real
Operator. - Ar
- Real
Operator. It is converted into aNumPy arrayusingto_matrix. - E
- Real
OperatororNone(then assumed to be the identity). - Er
- Real
OperatororNone(then assumed to be the identity). It is converted into aNumPy arrayusingto_matrix. - B
- Real
OperatororNone. - Br
- Real
OperatororNone. It is converted into aVectorArrayusingBr.as_source_array(). - C
- Real
OperatororNone. - Cr
- Real
OperatororNone. It is converted into aVectorArrayusingCr.as_range_array().
Returns
- V
- Returned if
BandBrare given,VectorArrayfromA.source. - W
- Returned if
CandCrare given,VectorArrayfromA.source.
Raises
- ValueError
- If
VandWcannot be returned.
This module provides generic time-stepping algorithms for the solution of instationary problems.
The algorithms are generic in the sense that each algorithms operates exclusively
on Operators and VectorArrays. In particular, the algorithms
can also be used to turn an arbitrary stationary Discretization provided
by an external library into an instationary Discretization.
Currently, implementations of explicit_euler and implicit_euler
time-stepping are provided. The TimeStepperInterface defines a
common interface that has to be fulfilled by the time-steppers used
by InstationaryDiscretization. The classes ExplicitEulerTimeStepper
and ImplicitEulerTimeStepper encapsulate explicit_euler and
implicit_euler to provide this interface.
-
class
pymor.algorithms.timestepping.ExplicitEulerTimeStepper(nt)[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperInterfaceExplicit Euler time-stepper.
Solves equations of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- nt
- The number of time-steps the time-stepper will perform.
Methods
ExplicitEulerTimeSteppersolveImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
- The time at which to begin time-stepping.
- end_time
- The time until which to perform time-stepping.
- initial_data
- The solution vector at
initial_time. - operator
- The
OperatorA. - rhs
- The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
class
pymor.algorithms.timestepping.ImplicitEulerTimeStepper(nt, solver_options='operator')[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperInterfaceImplict Euler time-stepper.
Solves equations of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- nt
- The number of time-steps the time-stepper will perform.
- solver_options
- The
solver_optionsused to invertM + dt*A. The special values'mass'and'operator'are recognized, in which case the solver_options of M (resp. A) are used.
Methods
ImplicitEulerTimeSteppersolveImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
- The time at which to begin time-stepping.
- end_time
- The time until which to perform time-stepping.
- initial_data
- The solution vector at
initial_time. - operator
- The
OperatorA. - rhs
- The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
class
pymor.algorithms.timestepping.TimeStepperInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInterface for time-stepping algorithms.
Algorithms implementing this interface solve time-dependent problems of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Time-steppers used by
InstationaryDiscretizationhave to fulfill this interface.Methods
TimeStepperInterfacesolveImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
- The time at which to begin time-stepping.
- end_time
- The time until which to perform time-stepping.
- initial_data
- The solution vector at
initial_time. - operator
- The
OperatorA. - rhs
- The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
-
pymor.algorithms.timestepping.explicit_euler(A, F, U0, t0, t1, nt, mu=None, num_values=None)[source]¶
-
class
pymor.algorithms.to_matrix.ToMatrixRules(format, mu)[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
RuleTableappend_rule,apply,apply_children,get_children,insert_rule,replace_childrenBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ToMatrixRulesaction_AdjointOperator,action_BlockOperator,action_ComponentProjection,action_Concatenation,action_IdentityOperator,action_LincombOperator,action_NumpyMatrixOperator,action_VectorArrayOperator,action_ZeroOperator,rulesBasicInterfacelogger,logging_disabled,name,uid
-
pymor.algorithms.to_matrix.to_matrix(op, format=None, mu=None)[source]¶ Convert a linear
Operatorto a matrix.Parameters
- op
- The
Operatorto convert. - format
- Format of the resulting matrix:
NumPy arrayif ‘dense’, otherwise the appropriateSciPy spmatrix. IfNone, a choice between dense and sparse format is automatically made. - mu
- The
Parameterfor which to convertop.
Returns
- res
- The matrix equivalent to
op.
pymor.analyticalproblems package¶
Submodules¶
-
pymor.analyticalproblems.burgers.burgers_problem(v=1.0, circle=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]¶ One-dimensional Burgers-type problem.
The problem is to solve
∂_t u(x, t, μ) + ∂_x (v * u(x, t, μ)^μ) = 0 u(x, 0, μ) = u_0(x)for u with t in [0, 0.3] and x in [0, 2].
Parameters
- v
- The velocity v.
- circle
- If
True, impose periodic boundary conditions. Otherwise Dirichlet left, outflow right. - initial_data_type
- Type of initial data (
'sin'or'bump'). - parameter_range
- The interval in which μ is allowed to vary.
-
pymor.analyticalproblems.burgers.burgers_problem_2d(vx=1.0, vy=1.0, torus=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]¶ Two-dimensional Burgers-type problem.
The problem is to solve
∂_t u(x, t, μ) + ∇ ⋅ (v * u(x, t, μ)^μ) = 0 u(x, 0, μ) = u_0(x)for u with t in [0, 0.3], x in [0, 2] x [0, 1].
Parameters
- vx
- The x component of the velocity vector v.
- vy
- The y component of the velocity vector v.
- torus
- If
True, impose periodic boundary conditions. Otherwise, Dirichlet left and bottom, outflow top and right. - initial_data_type
- Type of initial data (
'sin'or'bump'). - parameter_range
- The interval in which μ is allowed to vary.
-
class
pymor.analyticalproblems.elliptic.StationaryProblem(domain, rhs=None, diffusion=None, advection=None, nonlinear_advection=None, nonlinear_advection_derivative=None, reaction=None, nonlinear_reaction=None, nonlinear_reaction_derivative=None, dirichlet_data=None, neumann_data=None, robin_data=None, functionals=None, parameter_space=None, name=None)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceLinear elliptic problem description.
The problem consists in solving
- ∇ ⋅ [d(x, μ) ∇ u(x, μ)] + ∇ ⋅ [f(x, u(x, μ), μ)] + c(x, u(x, μ), μ) = f(x, μ)
for u.
Parameters
- domain
- A
DomainDescriptionof the domain the problem is posed on. - rhs
- The
Functionf(x, μ).rhs.dim_domainhas to agree with the dimension ofdomain, whereasrhs.shape_rangehas to be(). - diffusion
- The
Functiond(x, μ) withshape_rangeof either()or(dim domain, dim domain). - advection
- The
Functionf, only depending on x, withshape_rangeof(dim domain,). - nonlinear_advection
- The
Functionf, only depending on u, withshape_rangeof(dim domain,). - nonlinear_advection_derivative
- The derivative of f, only depending on u, with respect to u.
- reaction
- The
Functionc, only depending on x, withshape_rangeof(). - nonlinear_reaction
- The
Functionc, only depending on u, withshape_rangeof(). - nonlinear_reaction_derivative
- The derivative of the
Functionc, only depending on u, withshape_rangeof(). - dirichlet_data
Functionproviding the Dirichlet boundary values.- neumann_data
Functionproviding the Neumann boundary values.- robin_data
- Tuple of two
Functionsproviding the Robin parameter and boundary values. - functionals
Dictof additional functionals to assemble. Each value must be a tuple of the form(functional_type, data)wherefunctional_typeis a string defining the type of functional to assemble anddatais aFunctionholding the corresponding coefficient function. Currently implementedfunctional_typesare:l2: Evaluate the l2-product with the given data function. l2_boundary: Evaluate the l2-product with the given data function on the boundary. - parameter_space
ParameterSpacefor the problem.- name
- Name of the problem.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
-
domain¶
-
rhs¶
-
diffusion¶
-
advection¶
-
nonlinear_advection¶
-
nonlinear_advection_derivative¶
-
reaction¶
-
nonlinear_reaction¶
-
nonlinear_reaction_derivative¶
-
dirichlet_data¶
-
neumann_data¶
-
robin_data¶
-
functionals¶
-
pymor.analyticalproblems.helmholtz.helmholtz_problem(domain=RectDomain([[0 0], [1 1]]), rhs=None, parameter_range=(0.0, 100.0), dirichlet_data=None, neumann_data=None)[source]¶ Helmholtz equation problem.
This problem is to solve the Helmholtz equation
- ∆ u(x, k) - k^2 u(x, k) = f(x, k)
on a given domain.
Parameters
- domain
- A
DomainDescriptionof the domain the problem is posed on. - rhs
- The
Functionf(x, μ). - parameter_range
- A tuple
(k_min, k_max)describing the interval in which k is allowd to vary. - dirichlet_data
Functionproviding the Dirichlet boundary values.- neumann_data
Functionproviding the Neumann boundary values.
-
class
pymor.analyticalproblems.instationary.InstationaryProblem(stationary_part, initial_data, T=1.0, parameter_space=None, name=None)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstationary problem description.
This class describes an instationary problem of the form
| ∂_t u(x, t, μ) + A(u(x, t, μ), t, μ) = f(x, t, μ), | u(x, 0, μ) = u_0(x, μ)
where A, f are given by the problem’s
stationary_partand t is allowed to vary in the interval [0, T].Parameters
- stationary_part
- The stationary part of the problem.
- initial_data
Functionproviding the initial values u_0.- T
- The final time T.
- parameter_space
ParameterSpacefor the problem.- name
- Name of the problem.
Methods
InstationaryProblemwith_ImmutableInterfacegenerate_sid,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
InstationaryProblemparameter_space,stationary_part,T,with_argumentsImmutableInterfaceadd_with_arguments,sid,sid_ignoreBasicInterfacelogger,logging_disabled,name,uid-
T¶
-
stationary_part¶
-
parameter_space¶
-
name¶
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
pymor.analyticalproblems.thermalblock.thermal_block_problem(num_blocks=(3, 3), parameter_range=(0.1, 1))[source]¶ Analytical description of a 2D ‘thermal block’ diffusion problem.
The problem is to solve the elliptic equation
- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = f(x, μ)
on the domain [0,1]^2 with Dirichlet zero boundary values. The domain is partitioned into nx x ny blocks and the diffusion function d(x, μ) is constant on each such block (i,j) with value μ_ij.
---------------------------- | | | | | μ_11 | μ_12 | μ_13 | | | | | |--------------------------- | | | | | μ_21 | μ_22 | μ_23 | | | | | ----------------------------
Parameters
- num_blocks
- The tuple
(nx, ny) - parameter_range
- A tuple
(μ_min, μ_max). EachParametercomponent μ_ij is allowed to lie in the interval [μ_min, μ_max].
pymor.bindings package¶
Submodules¶
-
pymor.bindings.scipy.apply_inverse(op, V, options=None, least_squares=False, check_finite=True, default_solver='scipy_spsolve', default_least_squares_solver='scipy_least_squares_lsmr')[source]¶ Solve linear equation system.
Applies the inverse of
opto the vectors inrhsusing SciPy.Parameters
- op
- The linear, non-parametric
Operatorto invert. - rhs
VectorArrayof right-hand sides for the equation system.- options
- The
solver_optionsto use (seesolver_options). - least_squares
- If
True, return least squares solution. - check_finite
- Test if solution only contains finite values.
- default_solver
- Default solver to use (scipy_spsolve, scipy_bicgstab, scipy_bicgstab_spilu, scipy_lgmres, scipy_least_squares_lsmr, scipy_least_squares_lsqr).
- default_least_squares_solver
- Default solver to use for least squares problems (scipy_least_squares_lsmr, scipy_least_squares_lsqr).
Returns
VectorArrayof the solution vectors.Defaults
check_finite, default_solver, default_least_squares_solver (see
pymor.core.defaults)
-
pymor.bindings.scipy.lyap_dense_solver_options()[source]¶ Return available dense Lyapunov equation solvers with default solver options for the SciPy backend.
Returns
A dict of available solvers with default solver options.
-
pymor.bindings.scipy.lyap_lrcf_solver_options()[source]¶ Returns available Lyapunov equation solvers with default solver options for the SciPy backend.
Returns
A dict of available solvers with default solver options.
-
pymor.bindings.scipy.pos_ricc_lrcf_solver_options()[source]¶ Returns available positive Riccati equation solvers with default solver options for the SciPy backend.
Returns
A dict of available solvers with default solver options.
-
pymor.bindings.scipy.ricc_lrcf_solver_options()[source]¶ Returns available Riccati equation solvers with default solver options for the SciPy backend.
Returns
A dict of available solvers with default solver options.
-
pymor.bindings.scipy.solve_lyap_dense(A, E, B, trans=False, options=None)[source]¶ Compute the solution of a Lyapunov equation.
See
pymor.algorithms.lyapunov.solve_lyap_densefor a general description.This function uses
scipy.linalg.solve_continuous_lyapunov, which is a dense solver for Lyapunov equations with E=I.Note
If E is not
None, the problem will be reduced to a standard continuous-time algebraic Lyapunov equation by inverting E.Parameters
- A
- The operator A as a 2D
NumPy array. - E
- The operator E as a 2D
NumPy arrayorNone. - B
- The operator B as a 2D
NumPy array. - trans
- Whether the first operator in the Lyapunov equation is transposed.
- options
- The solver options to use (see
lyap_dense_solver_options).
Returns
- X
- Lyapunov equation solution as a
NumPy array.
-
pymor.bindings.scipy.solve_lyap_lrcf(A, E, B, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a Lyapunov equation.
See
pymor.algorithms.lyapunov.solve_lyap_lrcffor a general description.This function uses
scipy.linalg.solve_continuous_lyapunov, which is a dense solver for Lyapunov equations with E=I. Therefore, we assume A and E can be converted toNumPy arraysusingto_matrixand thatB.to_numpyis implemented.Note
If E is not
None, the problem will be reduced to a standard continuous-time algebraic Lyapunov equation by inverting E.Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - trans
- Whether the first
Operatorin the Lyapunov equation is transposed. - options
- The solver options to use (see
lyap_lrcf_solver_options).
Returns
- Z
- Low-rank Cholesky factor of the Lyapunov equation solution,
VectorArrayfromA.source.
-
pymor.bindings.scipy.solve_pos_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a positive Riccati equation.
See
pymor.algorithms.riccati.solve_pos_ricc_lrcffor a general description.This function uses
scipy.linalg.solve_continuous_are, which is a dense solver. Therefore, we assume allOperatorsandVectorArrayscan be converted toNumPy arraysusingto_matrixandto_numpy.Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - C
- The operator C as a
VectorArrayfromA.source. - R
- The operator R as a 2D
NumPy arrayorNone. - S
- The operator S as a
VectorArrayfromA.sourceorNone. - trans
- Whether the first
Operatorin the positive Riccati equation is transposed. - options
- The solver options to use (see
pos_ricc_lrcf_solver_options).
Returns
- Z
- Low-rank Cholesky factor of the positive Riccati equation
solution,
VectorArrayfromA.source.
-
pymor.bindings.scipy.solve_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a Riccati equation.
See
pymor.algorithms.riccati.solve_ricc_lrcffor a general description.This function uses
scipy.linalg.solve_continuous_are, which is a dense solver. Therefore, we assume allOperatorsandVectorArrayscan be converted toNumPy arraysusingto_matrixandto_numpy.Parameters
- A
- The
OperatorA. - E
- The
OperatorE orNone. - B
- The operator B as a
VectorArrayfromA.source. - C
- The operator C as a
VectorArrayfromA.source. - R
- The operator R as a 2D
NumPy arrayorNone. - S
- The operator S as a
VectorArrayfromA.sourceorNone. - trans
- Whether the first
Operatorin the Riccati equation is transposed. - options
- The solver options to use (see
ricc_lrcf_solver_options).
Returns
- Z
- Low-rank Cholesky factor of the Riccati equation solution,
VectorArrayfromA.source.
-
pymor.bindings.scipy.solver_options(bicgstab_tol=1e-15, bicgstab_maxiter=None, spilu_drop_tol=0.0001, spilu_fill_factor=10, spilu_drop_rule=None, spilu_permc_spec='COLAMD', spsolve_permc_spec='COLAMD', spsolve_keep_factorization=True, lgmres_tol=1e-05, lgmres_maxiter=1000, lgmres_inner_m=39, lgmres_outer_k=3, least_squares_lsmr_damp=0.0, least_squares_lsmr_atol=1e-06, least_squares_lsmr_btol=1e-06, least_squares_lsmr_conlim=100000000.0, least_squares_lsmr_maxiter=None, least_squares_lsmr_show=False, least_squares_lsqr_damp=0.0, least_squares_lsqr_atol=1e-06, least_squares_lsqr_btol=1e-06, least_squares_lsqr_conlim=100000000.0, least_squares_lsqr_iter_lim=None, least_squares_lsqr_show=False)[source]¶ Returns available solvers with default
solver_optionsfor the SciPy backend.Parameters
- bicgstab_tol
- See
scipy.sparse.linalg.bicgstab. - bicgstab_maxiter
- See
scipy.sparse.linalg.bicgstab. - spilu_drop_tol
- See
scipy.sparse.linalg.spilu. - spilu_fill_factor
- See
scipy.sparse.linalg.spilu. - spilu_drop_rule
- See
scipy.sparse.linalg.spilu. - spilu_permc_spec
- See
scipy.sparse.linalg.spilu. - spsolve_permc_spec
- See
scipy.sparse.linalg.spsolve. - spsolve_keep_factorization
- See
scipy.sparse.linalg.spsolve. - lgmres_tol
- See
scipy.sparse.linalg.lgmres. - lgmres_maxiter
- See
scipy.sparse.linalg.lgmres. - lgmres_inner_m
- See
scipy.sparse.linalg.lgmres. - lgmres_outer_k
- See
scipy.sparse.linalg.lgmres. - least_squares_lsmr_damp
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_atol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_btol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_conlim
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_maxiter
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_show
- See
scipy.sparse.linalg.lsmr. - least_squares_lsqr_damp
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_atol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_btol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_conlim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_iter_lim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_show
- See
scipy.sparse.linalg.lsqr.
Returns
A dict of available solvers with default
solver_options.Defaults
bicgstab_tol, bicgstab_maxiter, spilu_drop_tol, spilu_fill_factor, spilu_drop_rule, spilu_permc_spec, spsolve_permc_spec, spsolve_keep_factorization, lgmres_tol, lgmres_maxiter, lgmres_inner_m, lgmres_outer_k, least_squares_lsmr_damp, least_squares_lsmr_atol, least_squares_lsmr_btol, least_squares_lsmr_conlim, least_squares_lsmr_maxiter, least_squares_lsmr_show, least_squares_lsqr_atol, least_squares_lsqr_btol, least_squares_lsqr_conlim, least_squares_lsqr_iter_lim, least_squares_lsqr_show (see
pymor.core.defaults)
pymor.core package¶
Submodules¶
This module provides the caching facilities of pyMOR.
Any class that wishes to provide cached method calls should derive from
CacheableInterface. Methods which are to be cached can then
be marked using the cached decorator.
To ensure consistency, CacheableInterface derives from
ImmutableInterface: The return value of a cached method call should
only depend on its arguments as well as the immutable state of the class
instance.
Making this assumption, the keys for cache lookup are created from the following data:
- the instance’s state id in case of a
persistentCacheRegion, else the instance’suid,- the method’s
__name__,- the state id of the arguments,
- the state id of pyMOR’s global
defaults.
Note that instances of ImmutableInterface are allowed to have mutable
private attributes. It is the implementors responsibility not to break things.
(See this warning.)
Backends for storage of cached return values derive from CacheRegion.
Currently two backends are provided for memory-based and disk-based caching
(MemoryRegion and SQLiteRegion). The available regions
are stored in the module level cache_regions dict. The user can add
additional regions (e.g. multiple disk cache regions) as required.
CacheableInterface.cache_region specifies a key of the cache_regions dict
to select a cache region which should be used by the instance.
(Setting cache_region to None or 'none' disables caching.)
By default, a ‘memory’, a ‘disk’ and a ‘persistent’ cache region are configured. The
paths and maximum sizes of the disk regions, as well as the maximum number of keys of
the memory cache region can be configured via the
pymor.core.cache.default_regions.disk_path,
pymor.core.cache.default_regions.disk_max_size,
pymor.core.cache.default_regions.persistent_path,
pymor.core.cache.default_regions.persistent_max_size and
pymor.core.cache.default_regions.memory_max_keys defaults.
There two ways to disable and enable caching in pyMOR:
- Calling
disable_caching(enable_caching), to disable (enable) caching globally.- Calling
CacheableInterface.disable_caching(CacheableInterface.enable_caching) to disable (enable) caching for a given instance.
Caching of a method is only active if caching has been enabled both globally
(enabled by default) and on instance level. For debugging purposes, it is moreover
possible to set the environment variable PYMOR_CACHE_DISABLE=1 which overrides
any call to enable_caching.
A cache region can be emptied using CacheRegion.clear. The function
clear_caches clears each cache region registered in cache_regions.
-
class
pymor.core.cache.CacheRegion[source]¶ Bases:
objectBase class for all pyMOR cache regions.
Methods
CacheRegionclear,get,setAttributes
CacheRegionpersistent-
persistent¶ If
True, cache entries are kept between multiple program runs.
-
-
class
pymor.core.cache.CacheableInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceBase class for anything that wants to use our built-in caching.
Methods
Attributes
CacheableInterfacecache_region,sid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
cache_region¶ Name of the
CacheRegionto use. Must correspond to a key in thecache_regionsdict. IfNoneor'none', caching is disabled.
-
cached_method_call(method, *args, **kwargs)[source]¶ Call a given
methodand cache the return value.This method can be used as an alternative to the
cacheddecorator.Parameters
- method
- The method that is to be called. This has to be a method
of
self. - args
- Positional arguments for
method. - kwargs
- Keyword arguments for
method
Returns
The (possibly cached) return value of
method(*args, **kwargs).
-
enable_caching(region)[source]¶ Enable caching for this instance.
When setting the object’s cache region to a
persistentCacheRegion, the object’s state id will be computed.Parameters
- region
- Name of the
CacheRegionto use. Must correspond to a key in thecache_regionsdict. IfNoneor'none', caching is disabled.
-
-
class
pymor.core.cache.MemoryRegion(max_keys)[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
MemoryRegionclear,get,setAttributes
MemoryRegionNO_VALUECacheRegionpersistent
-
class
pymor.core.cache.SQLiteRegion(path, max_size, persistent)[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
SQLiteRegionclear,get,housekeeping,setAttributes
CacheRegionpersistent
-
pymor.core.cache.cached(function)[source]¶ Decorator to make a method of
CacheableInterfaceactually cached.
-
pymor.core.cache.default_regions(disk_path='/tmp/pymor.cache.docs', disk_max_size=1073741824, persistent_path='/tmp/pymor.persistent.cache.docs', persistent_max_size=1073741824, memory_max_keys=1000)[source]¶
This module contains pyMOR’s facilities for handling default values.
A default value in pyMOR is always the default value of some
function argument. To mark the value of an optional function argument
as a user-modifiable default value use the defaults decorator.
As an additional feature, if None is passed for such an argument,
its default value is used instead of None. This is useful
for writing code of the following form:
@default('option')
def algorithm(U, option=42):
...
def method_called_by_user(V, option_for_algorithm=None):
...
algorithm(U, option=option_for_algorithm)
...
If the user does not provide option_for_algorithm to
method_called_by_user, the default 42 is automatically chosen
without the implementor of method_called_by_user having to care
about this.
The user interface for handling default values in pyMOR is provided
by set_defaults, load_defaults_from_file,
write_defaults_to_file and print_defaults.
If pyMOR is imported, it will automatically search for a configuration
file named pymor_defaults.py in the current working directory.
If found, the file is loaded via load_defaults_from_file.
However, as a security precaution, the file will only be loaded if it is
owned by the user running the Python interpreter
(load_defaults_from_file uses exec to load the configuration).
As an alternative, the environment variable PYMOR_DEFAULTS can be
used to specify the path of a configuration file. If empty or set to
NONE, no configuration file will be loaded whatsoever.
Warning
The state of pyMOR’s global defaults enters the calculation of each
state id. Thus, if you first instantiate an immutable object and
then change the defaults, the resulting object will have a different
state id than if you first change the defaults. (This is necessary
as the object can save internal state upon initialization, which
depends on the state of the global defaults.) As a consequence, the
key generated for caching will depend on the
time the defaults have been changed. While no wrong results will be
produced, changing defaults at different times will cause unnecessary
cache misses and will pollute the cache with duplicate entries.
An exemption from this rule are defaults which are listed in the
sid_ignore argument of the defaults decorator. Such
defaults will not enter the state id calculation. This allows the
user to change defaults related to input/output, e.g.
logging, without breaking caching.
Before marking defaults as ignored in your own code, however, make
sure to double check that these defaults will not affect the result
of any mathematical algorithm.
-
class
pymor.core.defaults.DefaultContainer[source]¶ Bases:
objectInternal singleton class holding all default values defined in pyMOR.
Not to be used directly.
Methods
DefaultContainerget,import_all,keys,updateAttributes
DefaultContainersid
-
pymor.core.defaults.defaults(*args, sid_ignore=())[source]¶ Function decorator for marking function arguments as user-configurable defaults.
If a function decorated with
defaultsis called, the values of the marked default parameters are set to the values defined viaload_defaults_from_fileorset_defaultsin case no value has been provided by the caller of the function. Moreover, ifNoneis passed as a value for a default argument, the argument is set to its default value, as well. If no value has been specified usingset_defaultsorload_defaults_from_file, the default value provided in the function signature is used.If the argument
argof functionfin sub-modulemof packagepis marked as a default value, its value will be changeable by the aforementioned methods under the pathp.m.f.arg.Note that the
defaultsdecorator can also be used in user code.Parameters
- args
- List of strings containing the names of the arguments of the decorated function to mark as pyMOR defaults. Each of these arguments has to be a keyword argument (with a default value).
- sid_ignore
- List of strings naming the defaults in
argswhich should not enter state id calculation (because they do not affect the outcome of any computation). Such defaults will typically be IO related. Use with extreme caution!
-
pymor.core.defaults.defaults_sid()[source]¶ Return a state id for pyMOR’s global
defaults.This method is used for the calculation of state ids of
immutableobjects and forcachekey generation.
-
pymor.core.defaults.load_defaults_from_file(filename='./pymor_defaults.py')[source]¶ Loads
defaultvalues defined in configuration file.Suitable configuration files can be created via
write_defaults_to_file. The file is loaded via Python’sexecfunction, so be very careful with configuration files you have not created your own. You have been warned!Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.
Parameters
- filename
- Path of the configuration file.
-
pymor.core.defaults.print_defaults(import_all=True, shorten_paths=2)[source]¶ Print all
defaultvalues set in pyMOR.Parameters
- import_all
- While
print_defaultswill always print all defaults defined in loaded configuration files or set viaset_defaults, default values set in the function signature can only be printed after the modules containing these functions have been imported. Ifimport_allis set toTrue,print_defaultswill therefore first import all of pyMOR’s modules, to provide a complete lists of defaults. - shorten_paths
- Shorten the paths of all default values by
shorten_pathscomponents. The last two path components will always be printed.
-
pymor.core.defaults.set_defaults(defaults)[source]¶ Set
defaultvalues.This method sets the default value of function arguments marked via the
defaultsdecorator, overriding default values specified in the function signature or set earlier viaload_defaults_from_fileor previousset_defaultscalls.Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.
Parameters
- defaults
- Dictionary of default values. Keys are the full paths of the default
values (see
defaults).
-
pymor.core.defaults.write_defaults_to_file(filename='./pymor_defaults.py', packages=('pymor', ))[source]¶ Write the currently set
defaultvalues to a configuration file.The resulting file is an ordinary Python script and can be modified by the user at will. It can be loaded in a later session using
load_defaults_from_file.Parameters
- filename
- Name of the file to write to.
- packages
- List of package names.
To discover all default values that have been defined using the
defaultsdecorator,write_defaults_to_filewill recursively import all sub-modules of the named packages before creating the configuration file.
-
class
pymor.core.exceptions.AccuracyError[source]¶ Bases:
ExceptionIs raised if the result of a computation is inaccurate
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.ConstError[source]¶ Bases:
ExceptionI get thrown when you try to add a new member to a locked class instance
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.ExtensionError[source]¶ Bases:
ExceptionIs raised if a (basis) extension algorithm fails.
This will mostly happen during a basis extension when the new snapshot is already in the span of the basis.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.GmshError[source]¶ Bases:
ExceptionIs raised when a Gmsh related error occurs.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.ImageCollectionError(op)[source]¶ Bases:
ExceptionIs raised when a pymor.algorithms.image.estimate_image fails for given operator.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.InversionError[source]¶ Bases:
ExceptionIs raised if an operator inversion algorithm fails.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.LinAlgError[source]¶ Bases:
ExceptionIs raised if a linear algebra operation fails.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.NewtonError[source]¶ Bases:
ExceptionIs raised if the Newton algorithm fails to converge.
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.NoMatchingRuleError(obj)[source]¶ Bases:
NotImplementedErrorMethods
NotImplementedError__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
-
class
pymor.core.exceptions.QtMissing(msg=None)[source]¶ Bases:
ImportErrorRaise me where having importable Qt bindings is non-optional
Methods
Exception__new__BaseExceptionwith_tracebackAttributes
ImportErrormsg,name,pathBaseExceptionargs
-
class
pymor.core.exceptions.RuleNotMatchingError[source]¶ Bases:
NotImplementedErrorMethods
NotImplementedError__new__BaseExceptionwith_tracebackAttributes
BaseExceptionargs
This module provides base classes from which most classes in pyMOR inherit.
The purpose of these classes is to provide some common functionality for
all objects in pyMOR. The most notable features provided by BasicInterface
are the following:
BasicInterfacesets classUberMetaas metaclass which itself inherits fromabc.ABCMeta. Thus it is possible to define interface classes with abstract methods using theabstractmethoddecorator. There are also decorators for abstract class methods, static methods, and properties.- Using metaclass magic, each class deriving from
BasicInterfacecomes with its ownloggerinstance accessible through itsloggerattribute. The logger prefix is automatically set to the class name.- Logging can be disabled and re-enabled for each instance using the
BasicInterface.disable_loggingandBasicInterface.enable_loggingmethods.BasicInterface.uidprovides a unique id for each instance. Whileid(obj)is only guaranteed to be unique among all living Python objects,BasicInterface.uidwill be (almost) unique among all pyMOR objects that have ever existed, including previous runs of the application. This is achieved by building the id from a uuid4 which is newly created for each pyMOR run and a counter which is increased for any object that requests an uid.- If not set by the user to another value,
BasicInterface.nameis set to the name of the object’s class.
ImmutableInterface derives from BasicInterface and adds the following
functionality:
Using more metaclass magic, each instance which derives from
ImmutableInterfaceis locked after its__init__method has returned. Each attempt to change one of its attributes raises an exception. Private attributes (of the form_name) are exempted from this rule.A unique state id for the instance can be calculated by calling
generate_sidand is then stored as the object’ssidattribute. The state id is obtained by deterministically serializing the object’s state and then computing a checksum of the resulting byte stream.
ImmutableInterface.sid_ignorecan be set to a set of attribute names which should be excluded from state id calculation.
ImmutableInterface.with_can be used to create a copy of an instance with some changed attributes. E.g.obj.with_(a=x, b=y)creates a copy with the
aandbattributes ofobjset toxandy. (Note that in generalaandbdo not necessarily have to correspond to class attributes ofobj; it is up to the implementor to interpret the provided arguments.)ImmutableInterface.with_argumentsholds the set of allowed arguments.
ImmutableInterfaceprovides a default implementation ofwith_which works by creating a new instance, passing the arguments ofwith_to__init__. The missing__init__arguments are taken from instance attributes of the same name.
-
class
pymor.core.interfaces.BasicInterface[source]¶ Bases:
objectBase class for most classes in pyMOR.
Methods
BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
logger¶ A per-class instance of
logging.Loggerwith the class name as prefix.
-
logging_disabled¶ Trueif logging has been disabled.
-
name¶ The name of the instance. If not set by the user, the name is set to the class name.
-
uid¶ A unique id for each instance. The uid is obtained by using
UIDand is unique for all pyMOR objects ever created.
-
classmethod
has_interface_name()[source]¶ Trueif the class name ends withInterface. Used for introspection.
-
-
class
pymor.core.interfaces.ImmutableInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceBase class for immutable objects in pyMOR.
Instances of
ImmutableInterfaceare immutable in the sense that after execution of__init__, any modification of a non-private attribute will raise an exception.Warning
For instances of
ImmutableInterface, the result of member function calls should be completely determined by the function’s arguments together with the object’s state id and the current state of pyMOR’s globaldefaults.While, in principle, you are allowed to modify private members after instance initialization, this should never affect the outcome of future method calls. In particular, if you update any internal state after initialization, you have to ensure that this state is not affected by possible changes of the global
defaults.Also note that mutable private attributes will cause false cache misses when these attributes enter state id calculation. If your implementation uses such attributes, you should therefore add their names to the
sid_ignoreset.Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
add_with_arguments¶ Set of additional arguments for
with_. (Seewith_arguments.)
-
sid¶ The objects state id. Only available after
generate_sidhas been called.
-
with_arguments¶ Set of allowed keyword arguments for
with_. This is the union of the argument names of__init__and the names specified viaadd_with_arguments.
-
__setattr__(key, value)[source]¶ depending on _locked state I delegate the setattr call to object or raise an Exception
-
generate_sid(debug=False)[source]¶ Generate a unique state id for the given object.
The generated state id is stored in the object’s
sidattribute.Parameters
- debug
- If
True, produce some debugging output.
Returns
The generated state id.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
-
class
pymor.core.interfaces.ImmutableMeta(name, bases, namespace)[source]¶ Bases:
pymor.core.interfaces.UberMetaMetaclass for
ImmutableInterface.
-
class
pymor.core.interfaces.UID[source]¶ Bases:
objectProvides unique, quickly computed ids by combining a session UUID4 with a counter.
Attributes
UIDcounter,prefix,uid
-
class
pymor.core.interfaces.UberMeta(name, bases, namespace)[source]¶ Bases:
abc.ABCMeta
-
class
pymor.core.interfaces.classinstancemethod(cls_meth)[source]¶ Bases:
objectMethods
classinstancemethodinstancemethod
This module contains pyMOR’s logging facilities.
pyMOR’s logging facilities are based on the logging module of the
Python standard library. To obtain a new logger object use getLogger.
Logging can be configured via the set_log_format and
set_log_levels methods.
-
class
pymor.core.logger.ColoredFormatter[source]¶ Bases:
logging.FormatterA logging.Formatter that inserts tty control characters to color loglevel keyword output. Coloring can be disabled by setting the
PYMOR_COLORS_DISABLEenvironment variable to1.Methods
ColoredFormatterformatFormatterconverter,formatException,formatMessage,formatStack,formatTime,usesTimeAttributes
Formatterdefault_msec_format,default_time_format-
format(record)[source]¶ Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
-
-
class
pymor.core.logger.DummyLogger[source]¶ Bases:
objectMethods
DummyLoggerblock,critical,debug,error,exception,getChild,getEffectiveLevel,info,info2,info3,isEnabledFor,log,nop,warn,warningAttributes
DummyLoggerpropagate
-
pymor.core.logger.getLogger(module, level=None, filename='')[source]¶ Get the logger of the respective module for pyMOR’s logging facility.
Parameters
- module
- Name of the module.
- level
- If set,
logger.setLevel(level)is called (seesetLevel). - filename
- If not empty, path of an existing file where everything logged will be written to.
Defaults
filename (see
pymor.core.defaults)
-
pymor.core.logger.set_log_format(max_hierarchy_level=1, indent_blocks=True, block_timings=False)[source]¶ Set log levels for pyMOR’s logging facility.
Parameters
- max_hierarchy_level
- The number of components of the loggers name which are printed. (The first component is always stripped, the last component always preserved.)
- indent_blocks
- If
True, indent log messages inside a code block started withwith logger.block(...). - block_timings
- If
True, measure the duration of a code block started withwith logger.block(...).
Defaults
max_hierarchy_level, indent_blocks, block_timings (see
pymor.core.defaults)
-
pymor.core.logger.set_log_levels(levels=None)[source]¶ Set log levels for pyMOR’s logging facility.
Parameters
- levels
- Dict of log levels. Keys are names of loggers (see
logging.getLogger), values are the log levels to set for the loggers of the given names (seesetLevel).
Defaults
levels (see
pymor.core.defaults)
This module contains methods for object serialization.
Instead of importing serialization functions from Python’s
pickle module directly, you should use the dump, dumps,
load, loads functions defined here. In particular, these
methods will use dumps_function to serialize
function objects which cannot be pickled by Python’s standard
methods. Note, however, pickling such methods should be avoided
since the implementation of dumps_function uses non-portable
implementation details of CPython to achieve its goals.
-
pymor.core.pickle._global_names(code_object)[source]¶ Return all names in code_object.co_names which are used in a LOAD_GLOBAL statement.
-
pymor.core.pickle.dumps_function(function)[source]¶ Tries hard to pickle a function object:
- The function’s code object is serialized using the
marshalmodule. - For all global names used in the function’s code object the corresponding object in the function’s global namespace is pickled. In case this object is a module, the modules __package__ name is pickled.
- All default arguments are pickled.
- All objects in the function’s closure are pickled.
Note that also this is heavily implementation specific and will probably only work with CPython. If possible, avoid using this method.
- The function’s code object is serialized using the
-
pymor.core.pickle.loads_function(s)[source]¶ Restores a function serialized with
dumps_function.
pymor.discretizations package¶
Submodules¶
-
class
pymor.discretizations.basic.DiscretizationBase(operators=None, products=None, estimator=None, visualizer=None, cache_region=None, name=None, **kwargs)[source]¶ Bases:
pymor.discretizations.interfaces.DiscretizationInterfaceBase class for
Discretizationsproviding some common functionality.Methods
Attributes
-
estimate(U, mu=None)[source]¶ Estimate the discretization error for a given solution.
The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional
Discretization.Parameters
- U
- The solution obtained by
solve. - mu
Parameterfor whichUhas been obtained.
Returns
The estimated error.
-
visualize(U, **kwargs)[source]¶ Visualize a solution
VectorArrayU.Parameters
- U
- The
VectorArrayfromsolution_spacethat shall be visualized. - kwargs
- See docstring of
self.visualizer.visualize.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
-
class
pymor.discretizations.basic.InstationaryDiscretization(T, initial_data, operator, rhs, mass=None, time_stepper=None, num_values=None, products=None, operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseGeneric class for discretizations of instationary problems.
This class describes instationary problems given by the equations:
M * ∂_t u(t, μ) + L(u(μ), t, μ) = F(t, μ) u(0, μ) = u_0(μ)for t in [0,T], where L is a (possibly non-linear) time-dependent
Operator, F is a time-dependent vector-likeOperator, and u_0 the initial data. The massOperatorM is assumed to be linear, time-independent andParameter-independent.Parameters
- T
- The final time T.
- initial_data
- The initial data
u_0. Either aVectorArrayof length 1 or (for theParameter-dependent case) a vector-likeOperator(i.e. a linearOperatorwithsource.dim == 1) which applied toNumpyVectorArray(np.array([1]))will yield the initial data for a givenParameter. - operator
- The
OperatorL. - rhs
- The right-hand side F.
- mass
- The mass
OperatorM. IfNone, the identity is assumed. - time_stepper
- The
time-stepperto be used bysolve. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - products
- A dict of product
Operatorsdefined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization. - operators
- A dict of additional
Operatorsassociated with the discretization. - parameter_space
- The
ParameterSpacefor which the discrete problem is posed. - estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, d)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, d, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of theCacheRegionto use.- name
- Name of the discretization.
Methods
Attributes
-
T¶ The final time T.
-
initial_data¶ The intial data u_0 given by a vector-like
Operator. The same asoperators['initial_data'].
-
rhs¶ The right-hand side F. The same as
operators['rhs'].
-
mass¶ The mass operator M. The same as
operators['mass'].
-
time_stepper¶ The provided
time-stepper.
-
to_lti(output='output_functional')[source]¶ Convert discretization to
LTISystem.This method interprets the given discretization as an
LTISystemin the following way:- self.operator -> A self.rhs -> B self.operators[output] -> C None -> D self.mass -> E
Parameters
- output
- Key in
self.operatorsto use as output functional.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
class
pymor.discretizations.basic.StationaryDiscretization(operator, rhs, products=None, operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseGeneric class for discretizations of stationary problems.
This class describes discrete problems given by the equation:
L(u(μ), μ) = F(μ)
with a vector-like right-hand side F and a (possibly non-linear) operator L.
Note that even when solving a variational formulation where F is a functional and not a vector, F has to be specified as a vector-like
Operator(mapping scalars to vectors). This ensures that in the complex case both L and F are anti-linear in the test variable.Parameters
- operator
- The
OperatorL. - rhs
- The vector F. Either a
VectorArrayof length 1 or a vector-likeOperator. - products
- A dict of inner product
Operatorsdefined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization. - operators
- A dict of additional
Operatorsassociated with the discretization. - parameter_space
- The
ParameterSpacefor which the discrete problem is posed. - estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, d)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, d, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of theCacheRegionto use.- name
- Name of the discretization.
Methods
Attributes
-
rhs¶ The right-hand side F. The same as
operators['rhs'].
-
class
pymor.discretizations.interfaces.DiscretizationInterface[source]¶ Bases:
pymor.core.cache.CacheableInterface,pymor.parameters.base.ParametricInterface for discretization objects.
A discretization object defines a discrete problem via its
classand theOperatorsit contains. Furthermore, discretizations can besolvedfor a givenParameterresulting in a solutionVectorArray.Methods
Attributes
-
solution_space¶ VectorSpaceof theVectorArraysreturned bysolve.
-
linear¶ Trueif the discretization describes a linear problem.
-
operators¶ Dictionary of all
Operatorscontained in the discretization (seeGenericRBReductorfor a usage example).
-
estimate(U, mu=None)[source]¶ Estimate the discretization error for a given solution.
The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional
Discretization.Returns
The estimated error.
-
solve(mu=None, **kwargs)[source]¶ Solve the discrete problem for the
Parametermu.The result will be
cachedin case caching has been activated for the given discretization.Parameters
- mu
Parameterfor which to solve.
Returns
The solution given as a
VectorArray.
-
visualize(U, **kwargs)[source]¶ Visualize a solution
VectorArrayU.Parameters
- U
- The
VectorArrayfromsolution_spacethat shall be visualized.
-
-
class
pymor.discretizations.iosys.InputOutputSystem(input_space, output_space, cont_time=True, cache_region='memory', name=None, **kwargs)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseBase class for input-output systems.
Methods
Attributes
-
bode(w)[source]¶ Evaluate the transfer function on the imaginary axis.
Parameters
- w
- Angular frequencies at which to compute the transfer function.
Returns
- tfw
- Transfer function values at frequencies in
w,NumPy arrayof shape(len(w), self.p, self.m).
-
mag_plot(w, ax=None, ord=None, Hz=False, dB=False, **mpl_kwargs)[source]¶ Draw the magnitude Bode plot.
Parameters
- w
- Angular frequencies at which to evaluate the transfer function.
- ax
- Axis to which to plot.
If not given,
matplotlib.pyplot.gcais used. - ord
- The order of the norm used to compute the magnitude (the default is the Frobenius norm).
- Hz
- Should the frequency be in Hz on the plot.
- dB
- Should the magnitude be in dB on the plot.
- mpl_kwargs
- Keyword arguments used in the matplotlib plot function.
Returns
- out
- List of matplotlib artists added.
-
-
class
pymor.discretizations.iosys.InputStateOutputSystem(input_space, state_space, output_space, cont_time=True, cache_region='memory', name=None, **kwargs)[source]¶ Bases:
pymor.discretizations.iosys.InputOutputSystemBase class for input-output systems with state space.
Methods
Attributes
-
class
pymor.discretizations.iosys.LTISystem(A, B, C, D=None, E=None, cont_time=True, solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Bases:
pymor.discretizations.iosys.InputStateOutputSystemClass for linear time-invariant systems.
This class describes input-state-output systems given by

if continuous-time, or

if discrete-time, where
,
,
,
,
and
are linear operators.Parameters
- A
- The
OperatorA. - B
- The
OperatorB. - C
- The
OperatorC. - D
- The
OperatorD orNone(then D is assumed to be zero). - E
- The
OperatorE orNone(then E is assumed to be identity). - cont_time
Trueif the system is continuous-time, otherwiseFalse.- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Methods
Attributes
-
n¶ The order of the system.
-
__mul__(other)[source]¶ Multiply (cascade) two
LTISystems.
-
eval_dtf(s)[source]¶ Evaluate the derivative of the transfer function.
The derivative of the transfer function at
is
Note
We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.
Parameters
- s
- Complex number.
Returns
- dtfs
- Derivative of transfer function evaluated at the complex
number
s,NumPy arrayof shape(self.p, self.m).
-
eval_tf(s)[source]¶ Evaluate the transfer function.
The transfer function at
is
Note
We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.
Parameters
- s
- Complex number.
Returns
- tfs
- Transfer function evaluated at the complex number
s,NumPy arrayof shape(self.p, self.m).
-
classmethod
from_abcde_files(files_basename, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Create
LTISystemfrom matrices stored in a .[ABCDE] files.Parameters
- files_basename
- The basename of files containing A, B, C, and optionally D and E.
- cont_time
Trueif the system is continuous-time, otherwiseFalse.- input_id
- Id of the input space.
- state_id
- Id of the state space.
- output_id
- Id of the output space.
- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Returns
- lti
- The
LTISystemwith operators A, B, C, D, and E.
-
classmethod
from_files(A_file, B_file, C_file, D_file=None, E_file=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Create
LTISystemfrom matrices stored in separate files.Parameters
- A_file
- The name of the file (with extension) containing A.
- B_file
- The name of the file (with extension) containing B.
- C_file
- The name of the file (with extension) containing C.
- D_file
Noneor the name of the file (with extension) containing D.- E_file
Noneor the name of the file (with extension) containing E.- cont_time
Trueif the system is continuous-time, otherwiseFalse.- input_id
- Id of the input space.
- state_id
- Id of the state space.
- output_id
- Id of the output space.
- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Returns
- lti
- The
LTISystemwith operators A, B, C, D, and E.
-
classmethod
from_mat_file(file_name, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Create
LTISystemfrom matrices stored in a .mat file.Parameters
- file_name
- The name of the .mat file (extension .mat does not need to be included) containing A, B, C, and optionally D and E.
- cont_time
Trueif the system is continuous-time, otherwiseFalse.- input_id
- Id of the input space.
- state_id
- Id of the state space.
- output_id
- Id of the output space.
- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Returns
- lti
- The
LTISystemwith operators A, B, C, D, and E.
-
classmethod
from_matrices(A, B, C, D=None, E=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Create
LTISystemfrom matrices.Parameters
- A
- The
NumPy arrayorSciPy spmatrixA. - B
- The
NumPy arrayorSciPy spmatrixB. - C
- The
NumPy arrayorSciPy spmatrixC. - D
- The
NumPy arrayorSciPy spmatrixD orNone(then D is assumed to be zero). - E
- The
NumPy arrayorSciPy spmatrixE orNone(then E is assumed to be identity). - cont_time
Trueif the system is continuous-time, otherwiseFalse.- input_id
- Id of the input space.
- state_id
- Id of the state space.
- output_id
- Id of the output space.
- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Returns
- lti
- The
LTISystemwith operators A, B, C, D, and E.
-
gramian(typ)[source]¶ Compute a Gramian.
Parameters
- typ
The type of the Gramian:
'c_lrcf': low-rank Cholesky factor of the controllability Gramian,'o_lrcf': low-rank Cholesky factor of the observability Gramian,'c_dense': dense controllability Gramian,'o_dense': dense observability Gramian,
Returns
If typ is
'c_lrcf'or'o_lrcf', then the Gramian factor as aVectorArrayfromself.A.source. If typ is'c_dense'or'o_dense', then the Gramian as aNumPy array.
-
hinf_norm(return_fpeak=False, ab13dd_equilibrate=False)[source]¶ Compute the H_infinity-norm of the
LTISystem.Parameters
- return_fpeak
- Should the frequency at which the maximum is achieved should be returned.
- ab13dd_equilibrate
- Should
slycot.ab13dduse equilibration.
Returns
- norm
- H_infinity-norm.
- fpeak
- Frequency at which the maximum is achieved (if
return_fpeakisTrue).
-
hsU()[source]¶ Left Hankel singular vectors.
Returns
- Uh
NumPy arrayof left singluar vectors.
-
hsV()[source]¶ Right Hankel singular vectors.
Returns
- Vh
NumPy arrayof right singluar vectors.
-
hsv()[source]¶ Hankel singular values.
Returns
- sv
- One-dimensional
NumPy arrayof singular values.
-
class
pymor.discretizations.iosys.SecondOrderSystem(M, E, K, B, Cp, Cv=None, D=None, cont_time=True, solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Bases:
pymor.discretizations.iosys.InputStateOutputSystemClass for linear second order systems.
This class describes input-output systems given by

if continuous-time, or

if discrete-time, where
,
,
,
,
,
, and
are linear operators.Parameters
- M
- The
OperatorM. - E
- The
OperatorE. - K
- The
OperatorK. - B
- The
OperatorB. - Cp
- The
OperatorCp. - Cv
- The
OperatorCv orNone(then Cv is assumed to be zero). - D
- The
OperatorD orNone(then D is assumed to be zero). - cont_time
Trueif the system is continuous-time, otherwiseFalse.- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Methods
Attributes
-
n¶ The order of the system (equal to M.source.dim).
-
eval_dtf(s)[source]¶ Evaluate the derivative of the transfer function.

Note
We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.
Parameters
- s
- Complex number.
Returns
- dtfs
- Derivative of transfer function evaluated at the complex
number
s,NumPy arrayof shape(self.p, self.m).
-
eval_tf(s)[source]¶ Evaluate the transfer function.
The transfer function at
is
Note
We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.
Parameters
- s
- Complex number.
Returns
- tfs
- Transfer function evaluated at the complex number
s,NumPy arrayof shape(self.p, self.m).
-
classmethod
from_matrices(M, E, K, B, Cp, Cv=None, D=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]¶ Create a second order system from matrices.
Parameters
- M
- The
NumPy arrayorSciPy spmatrixM. - E
- The
NumPy arrayorSciPy spmatrixE. - K
- The
NumPy arrayorSciPy spmatrixK. - B
- The
NumPy arrayorSciPy spmatrixB. - Cp
- The
NumPy arrayorSciPy spmatrixCp. - Cv
- The
NumPy arrayorSciPy spmatrixCv orNone(then Cv is assumed to be zero). - D
- The
NumPy arrayorSciPy spmatrixD orNone(then D is assumed to be zero). - cont_time
Trueif the system is continuous-time, otherwiseFalse.- solver_options
- The solver options to use to solve the Lyapunov equations.
- estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Returns
- lti
- The SecondOrderSystem with operators M, E, K, B, Cp, Cv, and D.
-
gramian(typ)[source]¶ Compute a second-order Gramian.
Parameters
- typ
The type of the Gramian:
'pc_lrcf': low-rank Cholesky factor of the position controllability Gramian,'vc_lrcf': low-rank Cholesky factor of the velocity controllability Gramian,'po_lrcf': low-rank Cholesky factor of the position observability Gramian,'vo_lrcf': low-rank Cholesky factor of the velocity observability Gramian,'pc_dense': dense position controllability Gramian,'vc_dense': dense velocity controllability Gramian,'po_dense': dense position observability Gramian,'vo_dense': dense velocity observability Gramian,
Returns
If typ is
'pc_lrcf','vc_lrcf','po_lrcf'or'vo_lrcf', then the Gramian factor as aVectorArrayfromself.M.source. If typ is'pc_dense','vc_dense','po_dense'or'vo_dense', then the Gramian as aNumPy array.
-
hinf_norm(return_fpeak=False, ab13dd_equilibrate=False)[source]¶ Compute the H_infinity-norm.
Parameters
- return_fpeak
- Should the frequency at which the maximum is achieved should be returned.
- ab13dd_equilibrate
- Should
slycot.ab13dduse equilibration.
Returns
- norm
- H_infinity-norm.
- fpeak
- Frequency at which the maximum is achieved (if
return_fpeakisTrue).
-
psv()[source]¶ Position singular values.
Returns
One-dimensional
NumPy arrayof singular values.
-
pvsv()[source]¶ Position-velocity singular values.
Returns
One-dimensional
NumPy arrayof singular values.
-
to_lti()[source]¶ Return a first order representation.
The first order representation

is returned.
Returns
- lti
LTISystemequivalent to the second order system.
-
vpsv()[source]¶ Velocity-position singular values.
Returns
One-dimensional
NumPy arrayof singular values.
-
vsv()[source]¶ Velocity singular values.
Returns
One-dimensional
NumPy arrayof singular values.
-
class
pymor.discretizations.iosys.TransferFunction(input_space, output_space, H, dH, cont_time=True, cache_region='memory', name=None)[source]¶ Bases:
pymor.discretizations.iosys.InputOutputSystemClass for systems represented by a transfer function.
This class describes input-output systems given by a transfer function
.Parameters
- input_space
- The input
VectorSpace. TypicallyNumpyVectorSpace(m, 'INPUT')where m is the number of inputs. - output_space
- The output
VectorSpace. TypicallyNumpyVectorSpace(p, 'OUTPUT')where p is the number of outputs. - H
- The transfer function defined at least on the open right complex
half-plane.
H(s)is aNumPy arrayof shape(p, m). - dH
- The complex derivative of
H. - cont_time
Trueif the system is continuous-time, otherwiseFalse.- cache_region
Noneor name of the cache region to use. Seepymor.core.cache.- name
- Name of the system.
Methods
Attributes
-
tf¶ The transfer function.
-
dtf¶ The complex derivative of the transfer function.
-
class
pymor.discretizations.mpi.MPIDiscretization(obj_id, operators, products=None, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseWrapper class for MPI distributed
Discretizations.Given a single-rank implementation of a
Discretization, this wrapper class uses the event loop frompymor.tools.mpito allow an MPI distributed usage of theDiscretization. The underlying implementation needs to be MPI aware. In particular, the discretization’ssolvemethod has to perform an MPI parallel solve of the discretization.Note that this class is not intended to be instantiated directly. Instead, you should use
mpi_wrap_discretization.Parameters
- obj_id
ObjectIdof the localDiscretizationon each rank.- operators
- Dictionary of all
Operatorscontained in the discretization, wrapped for use on rank 0. Usempi_wrap_discretizationto automatically wrap all operators of a given MPI-awareDiscretization. - products
- See
operators. - pickle_local_spaces
- See
MPIOperator. - space_type
- See
MPIOperator.
Methods
Attributes
-
class
pymor.discretizations.mpi.MPIVisualizer(d_obj_id)[source]¶
-
pymor.discretizations.mpi.mpi_wrap_discretization(local_discretizations, use_with=False, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]¶ Wrap MPI distributed local
Discretizationsto a globalDiscretizationon rank 0.Given MPI distributed local
Discretizationsreferred to by theObjectIdlocal_discretizations, return a newDiscretizationwhich manages these distributed discretizations from rank 0. This is done by first wrapping allOperatorsof theDiscretizationusingmpi_wrap_operator.Alternatively,
local_discretizationscan be a callable (with no arguments) which is then called on each rank to instantiate the localDiscretizations.When
use_withisFalse, anMPIDiscretizationis instantiated with the wrapped operators. A call tosolvewill then use an MPI parallel call to thesolvemethods of the wrapped localDiscretizationsto obtain the solution. This is usually what you want when the actual solve is performed by an implementation in the external solver.When
use_withisTrue,with_is called on the localDiscretizationon rank 0, to obtain a newDiscretizationwith the wrapped MPIOperators. This is mainly useful when the local discretizations are genericDiscretizationsas inpymor.discretizations.basicandsolveis implemented directly in pyMOR via operations on the containedOperators.Parameters
- local_discretizations
ObjectIdof the localDiscretizationson each rank or a callable generating theDiscretizations.- use_with
- See above.
- with_apply2
- See
MPIOperator. - pickle_local_spaces
- See
MPIOperator. - space_type
- See
MPIOperator.
pymor.discretizers package¶
Submodules¶
-
pymor.discretizers.cg.discretize_instationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None, preassemble=True)[source]¶ Discretizes an
InstationaryProblemwith aStationaryProblemas stationary part using finite elements.Parameters
- analytical_problem
- The
InstationaryProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid_type
- If not
None, this parameter is forwarded todomain_discretizerto specify the type of the generatedGrid. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - time_stepper
- The
time-stepperto be used bysolve. - nt
- If
time_stepperis not specified, the number of time steps for implicit Euler time stepping. - preassemble
- If
True, preassemble all operators in the resultingDiscretization.
Returns
- d
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.unassembled_d: In case preassembleisTrue, the generatedDiscretizationbefore preassembling operators.
-
pymor.discretizers.cg.discretize_stationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, grid=None, boundary_info=None, preassemble=True)[source]¶ Discretizes a
StationaryProblemusing finite elements.Parameters
- analytical_problem
- The
StationaryProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid_type
- If not
None, this parameter is forwarded todomain_discretizerto specify the type of the generatedGrid. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - preassemble
- If
True, preassemble all operators in the resultingDiscretization.
Returns
- d
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.unassembled_d: In case preassembleisTrue, the generatedDiscretizationbefore preassembling operators.
-
pymor.discretizers.disk.discretize_instationary_from_disk(parameter_file, T=None, steps=None, u0=None, time_stepper=None)[source]¶ Load a linear affinely decomposed
InstationaryDiscretizationfrom file.Similarly to
discretize_stationary_from_disk, the discretization is specified via anini.-file of the following form[system-matrices] L_1.mat: l_1(μ_1,...,μ_n) L_2.mat: l_2(μ_1,...,μ_n) ... [rhs-vectors] F_1.mat: f_1(μ_1,...,μ_n) F_2.mat: f_2(μ_1,...,μ_n) ... [mass-matrix] D.mat [initial-solution] u0: u0.mat [parameter] μ_1: a_1,b_1 ... μ_n: a_n,b_n [products] Prod1: P_1.mat Prod2: P_2.mat ... [time] T: final time steps: number of time steps
Parameters
- parameter_file
- Path to the ‘.ini’ parameter file.
- T
- End-time of desired solution. If
None, the value specified in the parameter file is used. - steps
- Number of time steps to. If
None, the value specified in the parameter file is used. - u0
- Initial solution. If
Nonethe initial solution is obtained from parameter file. - time_stepper
- The desired
time stepperto use. IfNone, implicit Euler time stepping is used.
Returns
- d
- The
InstationaryDiscretizationthat has been generated.
-
pymor.discretizers.disk.discretize_stationary_from_disk(parameter_file)[source]¶ Load a linear affinely decomposed
StationaryDiscretizationfrom file.The discretization is defined via an
.ini-style file as follows[system-matrices] L_1.mat: l_1(μ_1,...,μ_n) L_2.mat: l_2(μ_1,...,μ_n) ... [rhs-vectors] F_1.mat: f_1(μ_1,...,μ_n) F_2.mat: f_2(μ_1,...,μ_n) ... [parameter] μ_1: a_1,b_1 ... μ_n: a_n,b_n [products] Prod1: P_1.mat Prod2: P_2.mat ...
Here,
L_1.mat,L_2.mat, …,F_1.mat,F_2.mat, … are files containing matricesL_1,L_2, … and vectorsF_1.mat,F_2.mat, … which correspond to the affine components of the operator and right-hand side. The respective coefficient functionals, are given via the string expressionsl_1(...),l_2(...), …,f_1(...)in the (scalar-valued)Parametercomponentsw_1, …,w_n. The allowed lower and upper boundsa_i, b_ifor the componentμ_iare specified in the[parameters]section. The resulting operator and right-hand side are then of the formL(μ) = l_1(μ)*L_1 + l_2(μ)*L_2+ ... F(μ) = f_1(μ)*F_1 + f_2(μ)*L_2+ ...
In the
[products]section, an optional list of inner productsProd1,Prod2, .. with corresponding matricesP_1.mat,P_2.matcan be specified.Example:
[system-matrices] matrix1.mat: 1. matrix2.mat: 1. - theta**2 [rhs-vectors] rhs.mat: 1. [parameter] theta: 0, 0.5 [products] h1: h1.mat l2: mass.mat
Parameters
- parameter_file
- Path to the parameter file.
Returns
- d
- The
StationaryDiscretizationthat has been generated.
-
pymor.discretizers.fv.discretize_instationary_fv(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, num_flux='lax_friedrichs', lxf_lambda=1.0, eo_gausspoints=5, eo_intervals=1, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None, preassemble=True)[source]¶ Discretizes an
InstationaryProblemwith aStationaryProblemas stationary part using the finite volume method.Parameters
- analytical_problem
- The
InstationaryProblemto discretize. - diameter
- If not
None,diameteris passed to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). If further arguments should be passed to the discretizer, usefunctools.partial. IfNone,discretize_domain_defaultis used. - grid_type
- If not
None, this parameter is forwarded todomain_discretizerto specify the type of the generatedGrid. - num_flux
- The numerical flux to use in the finite volume formulation. Allowed
values are
'lax_friedrichs','engquist_osher','simplified_engquist_osher'(seepymor.operators.fv). - lxf_lambda
- The stabilization parameter for the Lax-Friedrichs numerical flux (ignored, if different flux is chosen).
- eo_gausspoints
- Number of Gauss points for the Engquist-Osher numerical flux (ignored, if different flux is chosen).
- eo_intervals
- Number of sub-intervals to use for integration when using Engquist-Osher numerical flux (ignored, if different flux is chosen).
- grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - time_stepper
- The
time-stepperto be used bysolve. - nt
- If
time_stepperis not specified, the number of time steps for implicit Euler time stepping. - preassemble
- If
True, preassemble all operators in the resultingDiscretization.
Returns
- d
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.unassembled_d: In case preassembleisTrue, the generatedDiscretizationbefore preassembling operators.
-
pymor.discretizers.fv.discretize_stationary_fv(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, num_flux='lax_friedrichs', lxf_lambda=1.0, eo_gausspoints=5, eo_intervals=1, grid=None, boundary_info=None, preassemble=True)[source]¶ Discretizes a
StationaryProblemusing the finite volume method.Parameters
- analytical_problem
- The
StationaryProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid_type
- If not
None, this parameter is forwarded todomain_discretizerto specify the type of the generatedGrid. - num_flux
- The numerical flux to use in the finite volume formulation. Allowed
values are
'lax_friedrichs','engquist_osher','simplified_engquist_osher'(seepymor.operators.fv). - lxf_lambda
- The stabilization parameter for the Lax-Friedrichs numerical flux (ignored, if different flux is chosen).
- eo_gausspoints
- Number of Gauss points for the Engquist-Osher numerical flux (ignored, if different flux is chosen).
- eo_intervals
- Number of sub-intervals to use for integration when using Engquist-Osher numerical flux (ignored, if different flux is chosen).
- grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - preassemble
- If
True, preassemble all operators in the resultingDiscretization.
Returns
- d
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.unassembled_d: In case preassembleisTrue, the generatedDiscretizationbefore preassembling operators.
pymor.domaindescriptions package¶
Submodules¶
-
class
pymor.domaindescriptions.basic.CircleDomain(domain=(0, 1))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with the topology of a circle, i.e. a line with identified end points.
Parameters
- domain
- List [x_l, x_r] providing the left and right endpoint.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
CircleDomaindim,domain,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
domain¶
-
class
pymor.domaindescriptions.basic.CylindricalDomain(domain=([0, 0], [1, 1]), top='dirichlet', bottom='dirichlet')[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a cylindrical domain.
Boundary types can be associated edgewise.
Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified.
- top
- The boundary type of the top edge.
- bottom
- The boundary type of the bottom edge.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
CylindricalDomainbottom,diameter,dim,domain,height,lower_left,top,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
domain¶
-
top¶
-
bottom¶
-
class
pymor.domaindescriptions.basic.LineDomain(domain=(0, 1), left='dirichlet', right='dirichlet')[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes an interval domain.
Boundary types can be associated edgewise.
Parameters
- domain
- List [x_l, x_r] providing the left and right endpoint.
- left
- The boundary type of the left endpoint.
- right
- The boundary type of the right endpoint.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
LineDomaindim,domain,left,right,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
domain¶
-
left¶
-
right¶
-
class
pymor.domaindescriptions.basic.RectDomain(domain=([0, 0], [1, 1]), left='dirichlet', right='dirichlet', top='dirichlet', bottom='dirichlet')[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a rectangular domain.
Boundary types can be associated edgewise.
Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain.
- left
- The boundary type of the left edge.
- right
- The boundary type of the right edge.
- top
- The boundary type of the top edge.
- bottom
- The boundary type of the bottom edge.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
RectDomainbottom,diameter,dim,domain,height,left,lower_left,right,top,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
domain¶
-
left¶
-
right¶
-
top¶
-
bottom¶
-
class
pymor.domaindescriptions.basic.TorusDomain(domain=([0, 0], [1, 1]))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with the topology of a torus.
Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified, as well as the bottom and top edge
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
TorusDomaindiameter,dim,domain,height,lower_left,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
domain¶
-
class
pymor.domaindescriptions.interfaces.DomainDescriptionInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceDescribes a geometric domain along with its boundary.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
DomainDescriptionInterfaceboundary_types,dim,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
dim¶ The dimension of the domain
-
boundary_types¶ Set of boundary types the domain has.
-
-
class
pymor.domaindescriptions.polygonal.CircularSectorDomain(angle, radius, arc='dirichlet', radii='dirichlet', num_points=100)[source]¶ Bases:
pymor.domaindescriptions.polygonal.PolygonalDomainDescribes a circular sector domain of variable radius.
Parameters
- angle
- The angle between 0 and 2*pi of the circular sector.
- radius
- The radius of the circular sector.
- arc
- The boundary type of the arc.
- radii
- The boundary type of the two radii.
- num_points
- The number of points of the polygonal chain approximating the circular boundary.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
CircularSectorDomainangle,arc,num_points,radii,radiusPolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
angle¶
-
radius¶
-
arc¶
-
radii¶
-
num_points¶
-
class
pymor.domaindescriptions.polygonal.DiscDomain(radius, boundary='dirichlet', num_points=100)[source]¶ Bases:
pymor.domaindescriptions.polygonal.PolygonalDomainDescribes a disc domain of variable radius.
Parameters
- radius
- The radius of the disc.
- boundary
- The boundary type of the boundary.
- num_points
- The number of points of the polygonal chain approximating the boundary.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
DiscDomainboundary,num_points,radiusPolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
radius¶
-
boundary¶
-
num_points¶
-
class
pymor.domaindescriptions.polygonal.PolygonalDomain(points, boundary_types, holes=None)[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with a polygonal boundary and polygonal holes inside the domain.
Parameters
- points
- List of points [x_0, x_1] that describe the polygonal chain that bounds the domain.
- boundary_types
- Either a dictionary
{boundary_type: [i_0, ...], boundary_type: [j_0, ...], ...}withi_0, ...being the ids of boundary segments for a given boundary type (0is the line connecting point0to1,1is the line connecting point1to2etc.), or a function that returns the boundary type for a given coordinate. - holes
- List of lists of points that describe the polygonal chains that bound the holes inside the domain.
Methods
ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
PolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
points¶
-
boundary_types¶
-
holes¶
pymor.domaindiscretizers package¶
Submodules¶
-
pymor.domaindiscretizers.default.discretize_domain_default(domain_description, diameter=0.01, grid_type=None)[source]¶ Mesh a
DomainDescriptionusing an appropriate default implementation.This method can discretize the following
DomainDescriptions:DomainDescription grid_type default RectDomainTriaGridX RectGridCylindricalDomainTriaGridX RectGridTorusDomainTriaGridX RectGridLineDomainOnedGridX CircleDomainOnedGridX PolygonalDomainGmshGridX Parameters
- domain_description
- A
DomainDescriptionof the domain to mesh. - diameter
- Maximal diameter of the codim-0 entities of the generated
Grid. - grid_type
- The class of the
Gridwhich is to be constructed. IfNone, a default choice is made according to the table above.
Returns
- grid
- The generated
Grid. - boundary_info
- The generated
BoundaryInfo.
-
pymor.domaindiscretizers.gmsh.discretize_gmsh(domain_description=None, geo_file=None, geo_file_path=None, msh_file_path=None, mesh_algorithm='del2d', clscale=1.0, options='', refinement_steps=0)[source]¶ Mesh a
DomainDescriptionor an already existing Gmsh GEO-file using the Gmsh mesher.Parameters
- domain_description
- A
DomainDescriptionof thePolygonalDomainorRectDomainto discretize. Has to beNonewhengeo_fileis given. - geo_file
- File handle of the Gmsh Geo-file to discretize. Has to be
Nonewhendomain_descriptionis given. - geo_file_path
- Path of the created Gmsh GEO-file. When meshing a
PolygonalDomainorRectDomainandgeo_file_pathisNone, a temporary file will be created. Ifgeo_fileis specified, this is ignored and the path togeo_filewill be used. - msh_file_path
- Path of the created Gmsh MSH-file. If
None, a temporary file will be created. - mesh_algorithm
- The mesh generation algorithm to use (meshadapt, del2d, front2d).
- clscale
- Mesh element size scaling factor.
- options
- Other options to control the meshing procedure of Gmsh. See http://geuz.org/gmsh/doc/texinfo/gmsh.html#Command_002dline-options for all available options.
- refinement_steps
- Number of refinement steps to do after the initial meshing.
Returns
- grid
- The generated
GmshGrid. - boundary_info
- The generated
GmshBoundaryInfo.
pymor.functions package¶
Submodules¶
-
class
pymor.functions.basic.ConstantFunction(value=array(1.), dim_domain=1, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseA constant
Functionf: R^d -> R^shape(c), f(x) = c
Parameters
- value
- The constant c.
- dim_domain
- The dimension d.
- name
- The name of the function.
Methods
-
class
pymor.functions.basic.ExpressionFunction(expression, dim_domain=1, shape_range=(), parameter_type=None, values=None, name=None)[source]¶ Bases:
pymor.functions.basic.GenericFunctionTurns a Python expression given as a string into a
Function.Some
NumPyarithmetic functions like ‘sin’, ‘log’, ‘min’ are supported. For a full list see thefunctionsclass attribute.Warning
evalis used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!Parameters
- expression
- A Python expression of one variable
xand a parametermugiven as a string. - dim_domain
- The dimension of the domain.
- shape_range
- The shape of the values returned by the expression.
- parameter_type
- The
ParameterTypethe expression accepts. - values
- Dictionary of additional constants that can be used in
expressionwith their corresponding value. - name
- The name of the function.
Methods
-
class
pymor.functions.basic.FunctionBase[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceBase class for
Functionsproviding some common functionality.
-
class
pymor.functions.basic.GenericFunction(mapping, dim_domain=1, shape_range=(), parameter_type=None, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseWrapper making an arbitrary Python function between
NumPy arraysa properFunction.Note that a
GenericFunctioncan only bepickledif the function it is wrapping can be pickled (cf.dumps_function). For this reason, it is usually preferable to useExpressionFunctioninstead ofGenericFunction.Parameters
- mapping
The function to wrap. If
parameter_typeisNone, the function is of the formmapping(x). Ifparameter_typeis notNone, the function has to have the signaturemapping(x, mu). Moreover, the function is expected to be vectorized, i.e.:mapping(x).shape == x.shape[:-1] + shape_range.
- dim_domain
- The dimension of the domain.
- shape_range
- The shape of the values returned by the mapping.
- parameter_type
- The
ParameterTypethe mapping accepts. - name
- The name of the function.
Methods
-
class
pymor.functions.basic.LincombFunction(functions, coefficients, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseA
Functionrepresenting a linear combination ofFunctions.The linear coefficients can be provided either as scalars or as
ParameterFunctionals.Parameters
- functions
- List of
Functionswhose linear combination is formed. - coefficients
- A list of linear coefficients. A linear coefficient can
either be a fixed number or a
ParameterFunctional. - name
- Name of the function.
Methods
Attributes
-
functions¶
-
coefficients¶
-
class
pymor.functions.basic.ProductFunction(functions, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseA
Functionrepresenting a product ofFunctions.Parameters
- functions
- List of
Functionswhose product is formed. - name
- Name of the function.
Methods
Attributes
-
functions¶
-
class
pymor.functions.bitmap.BitmapFunction(filename, bounding_box=None, range=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseDefine a 2D
Functionvia a grayscale image.Parameters
- filename
- Path of the image representing the function.
- bounding_box
- Lower left and upper right coordinates of the domain of the function.
- range
- A pixel of value p is mapped to
(p / 255.) * range[1] + range[0].
Methods
-
class
pymor.functions.interfaces.FunctionInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterdependent analytical functions.Every
Functionis a map of the formf(μ): Ω ⊆ R^d -> R^(shape_range)
The returned values are
NumPy arraysof arbitrary (but fixed) shape. Note that NumPy distinguishes between one-dimensional arrays of length 1 (with shape(1,)) and zero-dimensional scalar arrays (with shape()). In pyMOR, we usually expect scalar-valued functions to haveshape_range == ().While the function might raise an error if it is evaluated for an argument not in the domain Ω, the exact behavior is left undefined.
Functions are vectorized in the sense, that if
x.ndim == k, thenf(x, μ)[i0, i1, ..., i(k-2)] == f(x[i0, i1, ..., i(k-2)], μ).
In particular,
f(x, μ).shape == x.shape[:-1] + shape_range.Methods
Attributes
-
dim_domain¶ The dimension d > 0.
-
shape_range¶ The shape of the function values.
-
pymor.grids package¶
Submodules¶
-
class
pymor.grids.boundaryinfos.AllDirichletBoundaryInfo(grid)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowhere the boundary type ‘dirichlet’ is attached to each boundary entity.Methods
AllDirichletBoundaryInfomaskBoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.grids.boundaryinfos.BoundaryInfoFromIndicators(grid, indicators, assert_unique_type=None, assert_some_type=None)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowhere the boundary types are determined by indicator functions.Parameters
- grid
- The
Gridto which theBoundaryInfois associated. - indicators
- Dict where each key is a boundary type and the corresponding value is a boolean valued function defined on the analytical domain which indicates if a point belongs to a boundary of the given boundary type (the indicator functions must be vectorized).
Methods
BoundaryInfoFromIndicatorsmaskBoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.grids.boundaryinfos.EmptyBoundaryInfo(grid)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowith no boundary types attached to any boundary.Methods
EmptyBoundaryInfomaskBoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.grids.boundaryinfos.SubGridBoundaryInfo(subgrid, grid, grid_boundary_info, new_boundary_type=None)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceDerives a
BoundaryInfofor aSubGrid.Parameters
- subrid
- The
SubGridfor which aBoundaryInfois created. - grid
- The parent
Grid. - grid_boundary_info
- The
BoundaryInfoof the parentGridfrom which to derive theBoundaryInfo - new_boundary_type
- The boundary type which is assigned to the new boundaries of
subgrid. IfNone, no boundary type is assigned.
Methods
SubGridBoundaryInfomaskBoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid
-
pymor.grids.constructions.flatten_grid(grid)[source]¶ This method is used by our visualizers to render n-dimensional grids which cannot be embedded into R^n by duplicating vertices which would have to be mapped to multiple points at once (think of grids on rectangular domains with identified edges).
Parameters
- grid
- The
Gridto flatten.
Returns
- subentities
- The
subentities(0, grid.dim)relation for the flattened grid. - coordinates
- The coordinates of the codim-
grid.dimentities. - entity_map
- Maps the indices of the codim-
grid.dimentities of the flattened grid to the indices of the corresponding entities in the original grid.
-
class
pymor.grids.defaultimpl.AffineGridDefaultImplementations[source]¶ Bases:
objectProvides default implementations for
AffineGrids.
-
class
pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations[source]¶ Bases:
objectProvides default informations for
ConformalTopologicalGrids.
-
class
pymor.grids.defaultimpl.ReferenceElementDefaultImplementations[source]¶ Bases:
objectProvides default implementations for
ReferenceElements.
-
class
pymor.grids.gmsh.GmshBoundaryInfo(grid, sections)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfofor aGmshGrid.Parameters
Methods
GmshBoundaryInfomaskBoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.grids.gmsh.GmshGrid(sections)[source]¶ Bases:
pymor.grids.unstructured.UnstructuredTriangleGridAn
UnstructuredTriangleGridbuilt from an existing Gmsh MSH-file.Parameters
- sections
- Parsed sections of the MSH-file as returned by
load_gmsh.
Methods
Attributes
-
pymor.grids.gmsh.load_gmsh(gmsh_file)[source]¶ Parse a Gmsh file and create a corresponding
GmshGridandGmshBoundaryInfo.Parameters
- gmsh_file
- File handle of the Gmsh MSH-file.
Returns
- grid
- The generated
GmshGrid. - boundary_info
- The generated
GmshBoundaryInfo.
-
class
pymor.grids.interfaces.AffineGridInterface[source]¶ Bases:
pymor.grids.defaultimpl.AffineGridDefaultImplementations,pymor.grids.interfaces.ConformalTopologicalGridInterfaceTopological grid with geometry where each codim-0 entity is affinely mapped to the same
ReferenceElement.The grid is completely determined via the subentity relation given by
subentitiesand the embeddings given byembeddings. In addition, onlysizeandreference_elementhave to be implemented. Cached default implementations for all other methods are provided byAffineGridDefaultImplementations.Methods
Attributes
ConformalTopologicalGridInterfacecache_region,dimCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
bounding_box()[source]¶ returns a
(2, dim)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
integration_elements(codim)[source]¶ retval[e]is given assqrt(det(A^T*A)), whereA = embeddings(codim)[0][e].
-
jacobian_inverse_transposed(codim)[source]¶ retval[e]is the transposed (pseudo-)inverse of the Jacobian ofembeddings(codim)[e].
-
quadrature_points(codim, order=None, npoints=None, quadrature_type='default')[source]¶ retval[e]is an array of quadrature points in global coordinates for the codim-codimentity with global indexe.The quadrature is of order
orderor hasnpointsintegration points. To integrate a functionfovereone has to formnp.dot(f(quadrature_points(codim, order)[e]), reference_element(codim).quadrature(order)[1]) * integration_elements(codim)[e]. # NOQA
-
reference_element(codim)[source]¶ The
ReferenceElementof the codim-codimentities.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
unit_outer_normals()[source]¶ retval[e,i]is the unit outer normal to the i-th codim-1 subentity of the codim-0 entitiy with global indexe.
-
-
class
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceAffineGridwith an additionalorthogonal_centersmethod.Methods
Attributes
ConformalTopologicalGridInterfacecache_region,dimCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
-
class
pymor.grids.interfaces.BoundaryInfoInterface[source]¶ Bases:
pymor.core.cache.CacheableInterfaceProvides boundary types for the boundaries of a given
ConformalTopologicalGrid.For every boundary type and codimension a mask is provided, marking grid entities of the respective type and codimension by their global index.
Methods
BoundaryInfoInterfaceboundaries,check_boundary_types,dirichlet_boundaries,dirichlet_mask,mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
boundary_types¶ set of all boundary types the grid has.
-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to the boundary typeboundary_type.
-
-
class
pymor.grids.interfaces.ConformalTopologicalGridInterface[source]¶ Bases:
pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations,pymor.core.cache.CacheableInterfaceA topological grid without hanging nodes.
The grid is completely determined via the subentity relation given by
subentities. In addition, onlysizehas to be implemented, cached default implementations for all other methods are provided byConformalTopologicalGridDefaultImplementations.Methods
Attributes
ConformalTopologicalGridInterfacecache_region,dimCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
dim¶ The dimension of the grid.
-
boundaries(codim)[source]¶ Returns the global indices of all codim-
codimboundary entities.By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For
codim != 1, a codim-codimentity is a boundary entity if it has a codim-1 sub/super-entity.
-
boundary_mask(codim)[source]¶ retval[e]is true iff the codim-codimentity with global indexeis a boundary entity.By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For
codim != 1, a codim-codimentity is a boundary entity if it has a codim-1 sub/super-entity.
-
neighbours(codim, neighbour_codim, intersection_codim=None)[source]¶ retval[e,n]is the global index of then-th codim-neighbour_codimentitiy of the codim-codimentityethat shares withea subentity of codimensionintersection_codim.If
intersection_codim == None, it is set tocodim + 1ifcodim == neighbour_codimand tomin(codim, neighbour_codim)otherwise.The default implementation is to compute the result from
subentities(codim, intersection_codim)andsuperentities(intersection_codim, neihbour_codim).
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.Only
subentities(codim, codim+1)has to be implemented; a default implementation is provided which evaluatessubentities(codim, subentity_codim)by computing the transitive closure ofsubentities(codim, codim+1).
-
superentities(codim, superentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-superentity_codimsuperentity of the codim-codimentity with global indexe.retval[e]is sorted by global index.The default implementation is to compute the result from
subentities(superentity_codim, codim).
-
-
class
pymor.grids.interfaces.ReferenceElementInterface[source]¶ Bases:
pymor.grids.defaultimpl.ReferenceElementDefaultImplementations,pymor.core.cache.CacheableInterfaceDefines a reference element.
All reference elements have the property that all subentities of a given codimension are of the same type. I.e. a three-dimensional reference element cannot have triangles and rectangles as faces at the same time.
Methods
Attributes
ReferenceElementInterfacecache_region,dim,volumeCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
dim¶ The dimension of the reference element
-
volume¶ The volume of the reference element
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.oned.OnedGrid(domain=(0, 1), num_intervals=4, identify_left_right=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceOne-dimensional
Gridon an interval.Parameters
- domain
- Tuple
(left, right)containing the left and right boundary of the domain. - num_intervals
- The number of codim-0 entities.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.rect.RectGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceBasic implementation of a rectangular
Gridon a rectangular domain.The global face, edge and vertex indices are given as follows
x1 ^ | 6--10---7--11---8 | | | 3 2 4 3 5 | | | 3---8---4---9---5 | | | 0 0 1 1 2 | | | 0---6---1---7---2 --> x0
Parameters
- num_intervals
- Tuple
(n0, n1)determining a grid withn0xn1codim-0 entities. - domain
- Tuple
(ll, ur)wherelldefines the lower left andurthe upper right corner of the domain. - identify_left_right
- If
True, the left and right boundaries are identified, i.e. the left-most codim-0 entities become neighbors of the right-most codim-0 entities. - identify_bottom_top
- If
True, the bottom and top boundaries are identified, i.e. the bottom-most codim-0 entities become neighbors of the top-most codim-0 entities.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
global_to_structured(codim)[source]¶ Returns an array which maps global codim-
codimindices to structured indices.I.e. if
GTS = global_to_structured(codim)andSTG = structured_to_global(codim), thenSTG[GTS[:, 0], GTS[:, 1]] == numpy.arange(size(codim)).
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
structured_to_global(codim)[source]¶ Returns an
NumPy arraywhich maps structured indices to global codim-codimindices.In other words
structured_to_global(codim)[i, j]is the global index of the i-th in x0-direction and j-th in x1-direction codim-codimentity of the grid.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
vertex_coordinates(dim)[source]¶ Returns an array of the x_dim coordinates of the grid vertices.
I.e.
centers(2)[structured_to_global(2)[i, j]] == np.array([vertex_coordinates(0)[i], vertex_coordinates(1)[j]])
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.referenceelements.Line[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
Linedim,volumeReferenceElementInterfacecache_regionCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Point[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
Pointdim,volumeReferenceElementInterfacecache_regionCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Square[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
Squaredim,volumeReferenceElementInterfacecache_regionCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Triangle[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
Triangledim,volumeReferenceElementInterfacecache_regionCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.subgrid.SubGrid(grid, entities)[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceA subgrid of a
Grid.Given a
Gridand a list of codim-0 entities we construct the minimal subgrid of the grid, containing all the given entities.Parameters
- grid
Gridof which a subgrid is to be created.- entities
NumPy arrayof global indices of the codim-0 entities which are to be contained in the subgrid.
Methods
Attributes
-
parent_grid¶ The
Gridfrom which the subgrid was constructed.Subgridonly stores aweakrefto the grid, so accessing this property might returnNoneif the original grid has been destroyed.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
indices_from_parent_indices(ind, codim)[source]¶ Maps a
NumPy arrayof indicies of codim-codimentites of the parent grid to indicies of the subgrid.Raises
- ValueError
- Not all provided indices correspond to entities contained in the subgrid.
-
parent_indices(codim)[source]¶ retval[e]is the index of thee-th codim-codimentity in the parent grid.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
class
pymor.grids.tria.TriaGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceBasic implementation of a triangular grid on a rectangular domain.
The global face, edge and vertex indices are given as follows
6---------10----------7---------11----------8 | \ / | \ / | | 22 10 18 | 23 11 19 | | \ / | \ / | 3 14 11 6 4 15 12 7 5 | / \ | / \ | | 14 2 26 | 15 3 27 | | / \ | / \ | 3----------8----------4----------9----------5 | \ / | \ / | | 20 8 16 | 21 9 17 | | \ / | \ / | 0 12 9 4 1 13 10 5 2 | / \ | / \ | | 12 0 24 | 13 1 25 | | / \ | / \ | 0----------6----------1----------7----------2
Parameters
- num_intervals
- Tuple
(n0, n1)determining a grid withn0xn1codim-0 entities. - domain
- Tuple
(ll, ur)wherelldefines the lower left andurthe upper right corner of the domain. - identify_left_right
- If
True, the left and right boundaries are identified, i.e. the left-most codim-0 entities become neighbors of the right-most codim-0 entities. - identify_bottom_top
- If
True, the bottom and top boundaries are identified, i.e. the bottom-most codim-0 entities become neighbors of the top-most codim-0 entities.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.unstructured.UnstructuredTriangleGrid(vertices, faces)[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceA generic unstructured, triangular grid.
Parameters
- vertices
- A (num_vertices, 2)-shaped
NumPy arraycontaining the coordinates of all vertices in the grid. The row numbers in the array will be the global indices of the given vertices (codim 2 entities). - faces
- A (num_faces, 3)-shaped
NumPy arraycontaining the global indices of the vertices which define a given triangle in the grid. The row numbers in the array will be the global indices of the given triangles (codim 0 entities).
Methods
Attributes
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
subentities(codim=0, subentity_codim=None)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
pymor.gui package¶
Submodules¶
This module provides a widget for displaying patch plots of
scalar data assigned to 2D-grids using OpenGL. This widget is not
intended to be used directly. Instead, use
visualize_patch or
PatchVisualizer.
-
class
pymor.gui.gl.ColorBarWidget(parent, U=None, vmin=None, vmax=None)[source]¶ Bases:
QGLWidgetMethods
ColorBarWidgetinitializeGL,paintEvent,resizeGL,set
-
class
pymor.gui.gl.GLPatchWidget(parent, grid, vmin=None, vmax=None, bounding_box=([0, 0], [1, 1]), codim=2)[source]¶ Bases:
QGLWidgetMethods
GLPatchWidgetinitializeGL,paintGL,resizeGL,set,set_coordinates
This module provides plotting support inside the Jupyter notebook.
To use these routines you first have to execute
%matplotlib notebook
inside the given notebook.
-
pymor.gui.jupyter.visualize_patch(grid, U, bounding_box=([0, 0], [1, 1]), codim=2, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, columns=2)[source]¶ Visualize scalar data associated to a two-dimensional
Gridas a patch plot.The grid’s
ReferenceElementmust be the triangle or square. The data can either be attached to the faces or vertices of the grid.Parameters
- grid
- The underlying
Grid. - U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- bounding_box
- A bounding box in which the grid is contained.
- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_colorbars
- If
True, use separate colorbars for each subplot. - rescale_colorbars
- If
True, rescale colorbars to data in each frame. - columns
- The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
This module provides a widgets for displaying plots of
scalar data assigned to one- and two-dimensional grids using
matplotlib. This widget is not intended to be used directly.
-
class
pymor.gui.matplotlib.Matplotlib1DWidget(parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100)[source]¶ Bases:
FigureCanvasQTAggMethods
Matplotlib1DWidgetset
-
class
pymor.gui.matplotlib.MatplotlibPatchAxes(figure, grid, bounding_box=None, vmin=None, vmax=None, codim=2, colorbar=True)[source]¶ Bases:
objectMethods
MatplotlibPatchAxesset
-
class
pymor.gui.matplotlib.MatplotlibPatchWidget(parent, grid, bounding_box=None, vmin=None, vmax=None, codim=2, dpi=100)[source]¶ Bases:
FigureCanvasQTAggMethods
MatplotlibPatchWidgetset
This module provides a few methods and classes for visualizing data associated to grids. We use the Qt widget toolkit for the GUI.
-
class
pymor.gui.qt.PlotMainWindow(U, plot, length=1, title=None)[source]¶ Bases:
objectBase class for plot main windows.
Methods
PlotMainWindowrewind,slider_changed,speed_changed,step_backward,step_forward,to_end,toggle_play,update_solution
-
pymor.gui.qt._launch_qt_app(main_window_factory, block)[source]¶ Wrapper to display plot in a separate process.
-
pymor.gui.qt.visualize_matplotlib_1d(grid, U, codim=1, title=None, legend=None, separate_plots=False, block=False)[source]¶ Visualize scalar data associated to a one-dimensional
Gridas a plot.The grid’s
ReferenceElementmust be the line. The data can either be attached to the subintervals or vertices of the grid.Parameters
- grid
- The underlying
Grid. - U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 1). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_plots
- If
True, use subplots to visualize multipleVectorArrays. - block
- If
True, block execution until the plot window is closed.
-
pymor.gui.qt.visualize_patch(grid, U, bounding_box=([0, 0], [1, 1]), codim=2, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, backend='gl', block=False, columns=2)[source]¶ Visualize scalar data associated to a two-dimensional
Gridas a patch plot.The grid’s
ReferenceElementmust be the triangle or square. The data can either be attached to the faces or vertices of the grid.Parameters
- grid
- The underlying
Grid. - U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- bounding_box
- A bounding box in which the grid is contained.
- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_colorbars
- If
True, use separate colorbars for each subplot. - rescale_colorbars
- If
True, rescale colorbars to data in each frame. - backend
- Plot backend to use (‘gl’ or ‘matplotlib’).
- block
- If
True, block execution until the plot window is closed. - columns
- The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
Defaults
backend (see
pymor.core.defaults)
-
class
pymor.gui.visualizers.OnedVisualizer(grid, codim=1, block=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceVisualize scalar data associated to a one-dimensional
Gridas a plot.The grid’s
ReferenceElementmust be the line. The data can either be attached to the subintervals or vertices of the grid.Parameters
- grid
- The underlying
Grid. - codim
- The codimension of the entities the data in
Uis attached to (either 0 or 1). - block
- If
True, block execution until the plot window is closed.
Methods
OnedVisualizervisualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
visualize(U, d, title=None, legend=None, block=None)[source]¶ Visualize the provided data.
Parameters
- U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.- d
- Filled in by
pymor.discretizations.DiscretizationBase.visualize(ignored). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - block
- If
True, block execution until the plot window is closed. IfNone, use the default provided during instantiation.
-
class
pymor.gui.visualizers.PatchVisualizer(grid, bounding_box=([0, 0], [1, 1]), codim=2, backend=None, block=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceVisualize scalar data associated to a two-dimensional
Gridas a patch plot.The grid’s
ReferenceElementmust be the triangle or square. The data can either be attached to the faces or vertices of the grid.Parameters
- grid
- The underlying
Grid. - bounding_box
- A bounding box in which the grid is contained.
- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - backend
- Plot backend to use (‘gl’, ‘matplotlib’, ‘jupyter’).
- block
- If
True, block execution until the plot window is closed.
Methods
PatchVisualizervisualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
visualize(U, d, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, block=None, filename=None, columns=2)[source]¶ Visualize the provided data.
Parameters
- U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- d
- Filled in by
pymor.discretizations.DiscretizationBase.visualize(ignored). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_colorbars
- If
True, use separate colorbars for each subplot. - rescale_colorbars
- If
True, rescale colorbars to data in each frame. - block
- If
True, block execution until the plot window is closed. IfNone, use the default provided during instantiation. - filename
- If specified, write the data to a VTK-file using
pymor.tools.vtkio.write_vtkinstead of displaying it. - columns
- The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
pymor.operators package¶
Submodules¶
-
class
pymor.operators.basic.OperatorBase[source]¶ Bases:
pymor.operators.interfaces.OperatorInterfaceBase class for
Operatorsproviding some default implementations.When implementing a new operator, it is usually advisable to derive from this class.
Methods
Attributes
-
apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).If the operator is a linear operator given by multiplication with a matrix M, then
apply2is given as:op.apply2(V, U) = V^T*M*U.
In the case of complex numbers, note that
apply2is anti-linear in the first variable by definition ofdot.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V), len(U))containing the 2-form evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V),) == (len(U),)containing the 2-form evaluations.
-
-
class
pymor.operators.basic.ProjectedOperator(operator, range_basis, source_basis, product=None, solver_options=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseGeneric
Operatorrepresenting the projection of anOperatorto a subspace.This operator is implemented as the concatenation of the linear combination with
source_basis, application of the originaloperatorand projection ontorange_basis. As such, this operator can be used to obtain a reduced basis projection of any givenOperator. However, no offline/online decomposition is performed, so this operator is mainly useful for testing before implementing offline/online decomposition for a specific application.This operator is instantiated in
pymor.algorithms.projection.projectas a default implementation for parametric or nonlinear operators.Parameters
- operator
- The
Operatorto project. - range_basis
- See
pymor.algorithms.projection.project. - source_basis
- See
pymor.algorithms.projection.project. - product
- See
pymor.algorithms.projection.project. - solver_options
- The
solver_optionsfor the projected operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
class
pymor.operators.block.BlockColumnOperator(blocks, source_id='STATE', range_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockOperatorBaseA column vector of arbitrary
Operators.Methods
Attributes
BlockColumnOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
adjoint_type¶ alias of
BlockRowOperator
-
-
class
pymor.operators.block.BlockDiagonalOperator(blocks, source_id='STATE', range_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockOperatorBlock diagonal
Operatorof arbitraryOperators.This is a specialization of
BlockOperatorfor the block diagonal case.Methods
Attributes
BlockOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
-
class
pymor.operators.block.BlockEmbeddingOperator(block_space, component, range_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockColumnOperatorMethods
Attributes
BlockColumnOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric
-
class
pymor.operators.block.BlockOperator(blocks, source_id='STATE', range_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockOperatorBaseA matrix of arbitrary
Operators.This operator can be
appliedto a compatibleBlockVectorArrays.Parameters
- blocks
- Two-dimensional array-like where each entry is an
OperatororNone.
Methods
Attributes
BlockOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
adjoint_type¶ alias of
BlockOperator
-
class
pymor.operators.block.BlockOperatorBase(blocks, source_id='STATE', range_id='STATE')[source]¶ Bases:
pymor.operators.basic.OperatorBaseMethods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
-
class
pymor.operators.block.BlockProjectionOperator(block_space, component, source_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockRowOperatorMethods
Attributes
BlockRowOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric
-
class
pymor.operators.block.BlockRowOperator(blocks, source_id='STATE', range_id='STATE')[source]¶ Bases:
pymor.operators.block.BlockOperatorBaseA row vector of arbitrary
Operators.Methods
Attributes
BlockRowOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
adjoint_type¶ alias of
BlockColumnOperator
-
-
class
pymor.operators.block.SecondOrderSystemOperator(E, K)[source]¶ Bases:
pymor.operators.block.BlockOperatorBlockOperator appearing in SecondOrderSystem.to_lti().
This represents a block operator

which satisfies

Methods
Attributes
BlockOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
-
class
pymor.operators.block.ShiftedSecondOrderSystemOperator(M, E, K, a, b)[source]¶ Bases:
pymor.operators.block.BlockOperatorBlockOperator appearing in second-order systems.
This represents a block operator

which satisfies

Methods
Attributes
BlockOperatoradjoint_type,blocked_range,blocked_sourceBlockOperatorBaseHOperatorInterfacelinear,range,solver_options,sourceImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uidParametricparameter_space,parameter_type,parametric-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
This module provides some operators for continuous finite element discretizations.
-
class
pymor.operators.cg.AdvectionOperatorP1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection
Operatorfor linear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]
The function
vis vector-valued.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- advection_function
- The
Functionv(x)withshape_range = (grid.dim, ). IfNone, constant one is assumed. - advection_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
-
class
pymor.operators.cg.AdvectionOperatorQ1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection
Operatorfor bilinear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]
The function
vhas to be vector-valued.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- advection_function
- The
Functionv(x)withshape_range = (grid.dim, ). IfNone, constant one is assumed. - advection_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
-
class
pymor.operators.cg.BoundaryDirichletFunctional(grid, dirichlet_data, boundary_info, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear finite element functional for enforcing Dirichlet boundary values.
Parameters
- grid
Gridfor which to assemble the functional.- dirichlet_data
Functionproviding the Dirichlet boundary values.- boundary_info
BoundaryInfodetermining the Dirichlet boundaries.- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.cg.BoundaryL2ProductFunctionalP1(grid, function, boundary_type=None, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear finite element functional representing the inner product with an L2-
Functionon the boundary.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - boundary_type
- The type of domain boundary (e.g. ‘neumann’) on which to assemble the functional.
If
Nonethe functional is assembled over the whole boundary. - dirichlet_clear_dofs
- If
True, set dirichlet boundary DOFs to zero. - boundary_info
- If
boundary_typeis specified ordirichlet_clear_dofsisTrue, theBoundaryInfodetermining which boundary entity belongs to which physical boundary. - order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.cg.BoundaryL2ProductFunctionalQ1(grid, function, boundary_type=None, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorBilinear finite element functional representing the inner product with an L2-
Functionon the boundary.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - boundary_type
- The type of domain boundary (e.g. ‘neumann’) on which to assemble the functional.
If
Nonethe functional is assembled over the whole boundary. - dirichlet_clear_dofs
- If
True, set dirichlet boundary DOFs to zero. - boundary_info
- If
boundary_typeis specified ordirichlet_clear_dofsisTrue, theBoundaryInfodetermining which boundary entity belongs to which physical boundary. - order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.cg.DiffusionOperatorP1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorDiffusion
Operatorfor linear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
The function
dcan be scalar- or matrix-valued.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The
Functiond(x)withshape_range == ()orshape_range = (grid.dim, grid.dim). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
-
class
pymor.operators.cg.DiffusionOperatorQ1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorDiffusion
Operatorfor bilinear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
The function
dcan be scalar- or matrix-valued.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The
Functiond(x)withshape_range == ()orshape_range = (grid.dim, grid.dim). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
-
class
pymor.operators.cg.InterpolationOperator(grid, function)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorVector-like Lagrange interpolation
Operatorfor continuous finite element spaces.Methods
-
class
pymor.operators.cg.L2ProductFunctionalP1(grid, function, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear finite element functional representing the inner product with an L2-
Function.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - dirichlet_clear_dofs
- If
True, set dirichlet boundary DOFs to zero. - boundary_info
BoundaryInfodetermining the Dirichlet boundaries in casedirichlet_clear_dofsis set toTrue.- order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
-
class
pymor.operators.cg.L2ProductFunctionalQ1(grid, function, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorBilinear finite element functional representing the inner product with an L2-
Function.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - dirichlet_clear_dofs
- If
True, set dirichlet boundary DOFs to zero. - boundary_info
BoundaryInfodetermining the Dirichlet boundaries in casedirichlet_clear_dofsis set toTrue.- order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
-
class
pymor.operators.cg.L2ProductP1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between linear finite element functions.Parameters
- grid
- The
Gridfor which to assemble the product. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- dirichlet_clear_rows
- If
True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if eitherdirichlet_clear_rowsordirichlet_clear_columnsisTrue, the diagonal entries are set to one. - coefficient_function
- Coefficient
Functionfor product withshape_range == (). IfNone, constant one is assumed. - solver_options
- The
solver_optionsfor the operator. - name
- The name of the product.
Methods
-
class
pymor.operators.cg.L2ProductQ1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between bilinear finite element functions.Parameters
- grid
- The
Gridfor which to assemble the product. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- dirichlet_clear_rows
- If
True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if eitherdirichlet_clear_rowsordirichlet_clear_columnsisTrue, the diagonal entries are set to one. - coefficient_function
- Coefficient
Functionfor product withshape_range == (). IfNone, constant one is assumed. - solver_options
- The
solver_optionsfor the operator. - name
- The name of the product.
Methods
-
class
pymor.operators.cg.RobinBoundaryOperator(grid, boundary_info, robin_data=None, order=2, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorRobin boundary
Operatorfor linear finite elements.The operator represents the contribution of Robin boundary conditions to the stiffness matrix, where the boundary condition is supposed to be given in the form
-[ d(x) ∇u(x) ] ⋅ n(x) = c(x) (u(x) - g(x))
dandnare the diffusion function (seeDiffusionOperatorP1) and the unit outer normal inx, whilecis the (scalar) Robin parameter function andgis the (also scalar) Robin boundary value function.Parameters
- grid
- The
Gridover which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- robin_data
- Tuple providing two
Functionsthat represent the Robin parameter and boundary value function. IfNone, the resulting operator is zero. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Module containing some constructions to obtain new operators from old ones.
-
class
pymor.operators.constructions.AdjointOperator(operator, source_product=None, range_product=None, name=None, with_apply_inverse=True, solver_options=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseRepresents the adjoint of a given linear
Operator.For a linear
Operatoropthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. If two products are given byP_sandP_r, then:op^*(v) = P_s^(-1) o op.H o P_r,
Thus, if
( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by application of the :attr:adjoint <pymor.operators.interface.OperatorInterface.H>`Operator.Parameters
- operator
- The
Operatorof which the adjoint is formed. - source_product
- If not
None, inner productOperatorfor the sourceVectorSpacew.r.t. which to take the adjoint. - range_product
- If not
None, inner productOperatorfor the rangeVectorSpacew.r.t. which to take the adjoint. - name
- If not
None, name of the operator. - with_apply_inverse
- If
True, provide ownapply_inverseandapply_inverse_adjointimplementations by calling these methods on the givenoperator. (Is set toFalsein the default implementation of andapply_inverse_adjoint.) - solver_options
- When
with_apply_inverseisFalse, thesolver_optionsto use for theapply_inversedefault implementation.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
class
pymor.operators.constructions.AffineOperator(operator, name=None)[source]¶ Bases:
pymor.operators.constructions.ProxyOperatorDecompose an affine
Operatorinto affine_shift and linear_part.Methods
-
class
pymor.operators.constructions.ComponentProjection(components, source, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseOperatorrepresenting the projection of aVectorArrayonto some of its components.Parameters
- components
- List or 1D
NumPy arrayof the indices of the vectorcomponentsthat are to be extracted by the operator. - source
- Source
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.Concatenation(operators, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseOperatorrepresenting the concatenation of twoOperators.Parameters
- operators
- Tuple of
Operatorsto concatenate.operators[-1]is the first applied operator,operators[0]is the last applied operator. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.ConstantOperator(value, source, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseA constant
Operatoralways returning the same vector.Parameters
- value
- A
VectorArrayof length 1 containing the vector which is returned by the operator. - source
- Source
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.FixedParameterOperator(operator, mu=None, name=None)[source]¶ Bases:
pymor.operators.constructions.ProxyOperatorMakes an
OperatorParameter-independent by setting a fixedParameter.Parameters
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
-
class
pymor.operators.constructions.IdentityOperator(space, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseThe identity
Operator.In other words:
op.apply(U) == U
Parameters
- space
- The
VectorSpacethe operator acts on. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.InducedNorm(product, raise_negative, tol, name)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInstantiated by
induced_norm. Do not use directly.Methods
-
class
pymor.operators.constructions.InverseAdjointOperator(operator, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseRepresents the inverse adjoint of a given
Operator.Parameters
- operator
- The
Operatorof which the inverse adjoint is formed. - name
- If not
None, name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
class
pymor.operators.constructions.InverseOperator(operator, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseRepresents the inverse of a given
Operator.Parameters
- operator
- The
Operatorof which the inverse is formed. - name
- If not
None, name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
class
pymor.operators.constructions.LincombOperator(operators, coefficients, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseLinear combination of arbitrary
Operators.This
Operatorrepresents a (possiblyParameterdependent) linear combination of a given list ofOperators.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- A list of linear coefficients. A linear coefficient can
either be a fixed number or a
ParameterFunctional. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).If the operator is a linear operator given by multiplication with a matrix M, then
apply2is given as:op.apply2(V, U) = V^T*M*U.
In the case of complex numbers, note that
apply2is anti-linear in the first variable by definition ofdot.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V), len(U))containing the 2-form evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
evaluate_coefficients(mu)[source]¶ Compute the linear coefficients for a given
Parameter.Parameters
- mu
Parameterfor which to compute the linear coefficients.
Returns
List of linear coefficients.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V),) == (len(U),)containing the 2-form evaluations.
-
class
pymor.operators.constructions.LinearOperator(operator, name=None)[source]¶ Bases:
pymor.operators.constructions.ProxyOperatorMark the wrapped
Operatorto be linear.Methods
-
class
pymor.operators.constructions.ProxyOperator(operator, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseForwards all interface calls to given
Operator.Mainly useful as base class for other
Operatorimplementations.Parameters
- operator
- The
Operatorto wrap. - name
- Name of the wrapping operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.SelectionOperator(operators, parameter_functional, boundaries, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseAn
Operatorselected from a list ofOperators.operators[i]is used ifparameter_functional(mu)is less or equal thanboundaries[i]and greater thanboundaries[i-1]:-infty ------- boundaries[i] ---------- boundaries[i+1] ------- infty | | --- operators[i] ---|---- operators[i+1] ----|---- operators[i+2] | |
Parameters
- operators
- List of
Operatorsfrom which oneOperatoris selected based on the givenParameter. - parameter_functional
- The
ParameterFunctionalused for the selection of oneOperator. - boundaries
- The interval boundaries as defined above.
- name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
class
pymor.operators.constructions.VectorArrayOperator(array, adjoint=False, space_id=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseWraps a
VectorArrayas anOperator.If
adjointisFalse, the operator maps fromNumpyVectorSpace(len(array))toarray.spaceby forming linear combinations of the vectors in the array with given coefficient arrays.If
adjoint == True, the operator maps fromarray.spacetoNumpyVectorSpace(len(array))by forming the inner products of the argument with the vectors in the given array.Parameters
- array
- The
VectorArraywhich is to be treated as an operator. - adjoint
- See description above.
- space_id
- Id of the
source(range)VectorSpacein caseadjointisFalse(True). - name
- The name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.VectorFunctional(vector, product=None, name=None)[source]¶ Bases:
pymor.operators.constructions.VectorArrayOperatorWrap a vector as a linear
Functional.Given a vector
vof dimensiond, this class represents the functionalf: R^d ----> R^1 u |---> (u, v)
where
( , )denotes the inner product given byproduct.In particular, if
productisNoneVectorFunctional(vector).as_source_array() == vector.
If
productis not none, we obtainVectorFunctional(vector).as_source_array() == product.apply(vector).
Parameters
- vector
VectorArrayof length 1 containing the vectorv.- product
Operatorrepresenting the scalar product to use.- name
- Name of the operator.
Methods
-
class
pymor.operators.constructions.VectorOperator(vector, name=None)[source]¶ Bases:
pymor.operators.constructions.VectorArrayOperatorWrap a vector as a vector-like
Operator.Given a vector
vof dimensiond, this class represents the operatorop: R^1 ----> R^d x |---> x⋅vIn particular:
VectorOperator(vector).as_range_array() == vector
Parameters
- vector
VectorArrayof length 1 containing the vectorv.- name
- Name of the operator.
Methods
-
class
pymor.operators.constructions.ZeroOperator(range, source, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseThe
Operatorwhich maps every vector to zero.Parameters
- range
- Range
VectorSpaceof the operator. - source
- Source
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
pymor.operators.constructions.induced_norm(product, raise_negative=True, tol=1e-10, name=None)[source]¶ Obtain induced norm of an inner product.
The norm of the vectors in a
VectorArrayU is calculated by callingproduct.pairwise_apply2(U, U, mu=mu).
In addition, negative norm squares of absolute value smaller than
tolare clipped to0. Ifraise_negativeisTrue, aValueErrorexception is raised if there are negative norm squares of absolute value larger thantol.Parameters
- product
- The inner product
Operatorfor which the norm is to be calculated. - raise_negative
- If
True, raise an exception if calculated norm is negative. - tol
- See above.
- name
- optional, if None product’s name is used
Returns
- norm
- A function
norm(U, mu=None)taking aVectorArrayUas input together with theParametermuwhich is passed to the product.
Defaults
raise_negative, tol (see
pymor.core.defaults)
-
class
pymor.operators.ei.EmpiricalInterpolatedOperator(operator, interpolation_dofs, collateral_basis, triangular, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseInterpolate an
Operatorusing Empirical Operator Interpolation.Let
Lbe anOperator,0 <= c_1, ..., c_M < L.range.dimindices of interpolation DOFs and letb_1, ..., b_M in R^(L.range.dim)be collateral basis vectors. If moreoverψ_j(U)denotes the j-th component ofU, the empirical interpolationL_EIofLw.r.t. the given data is given by| M | L_EI(U, μ) = ∑ b_i⋅λ_i such that | i=1 | | ψ_(c_i)(L_EI(U, μ)) = ψ_(c_i)(L(U, μ)) for i=0,...,M
Since the original operator only has to be evaluated at the given interpolation DOFs,
EmpiricalInterpolatedOperatorcallsrestrictedto obtain a restricted version of the operator which is used to quickly obtain the required evaluations. If therestrictedmethod, is not implemented, the full operator will be evaluated (which will lead to the same result, but without any speedup).The interpolation DOFs and the collateral basis can be generated using the algorithms provided in the
pymor.algorithms.eimodule.Parameters
- operator
- The
Operatorto interpolate. - interpolation_dofs
- List or 1D
NumPy arrayof the interpolation DOFsc_1, ..., c_M. - collateral_basis
VectorArraycontaining the collateral basisb_1, ..., b_M.- triangular
- If
True, assume that ψ_(c_i)(b_j) = 0 for i < j, which means that the interpolation matrix is triangular. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
class
pymor.operators.ei.ProjectedEmpiciralInterpolatedOperator(restricted_operator, interpolation_matrix, source_basis_dofs, projected_collateral_basis, triangular, source_id, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseA projected
EmpiricalInterpolatedOperator.Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
This module provides some operators for finite volume discretizations.
-
class
pymor.operators.fv.DiffusionOperator(grid, boundary_info, diffusion_function=None, diffusion_constant=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorFinite Volume Diffusion
Operator.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
Parameters
- grid
- The
Gridover which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The scalar-valued
Functiond(x). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
-
class
pymor.operators.fv.EngquistOsherFlux(flux, flux_derivative, gausspoints=5, intervals=1)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceEngquist-Osher numerical flux.
If
fis the analytical flux, andf'its derivative, the Engquist-Osher flux is given by:F(U_in, U_out, normal, vol) = vol * [c^+(U_in, normal) + c^-(U_out, normal)] U_in c^+(U_in, normal) = f(0)⋅normal + ∫ max(f'(s)⋅normal, 0) ds s=0 U_out c^-(U_out, normal) = ∫ min(f'(s)⋅normal, 0) ds s=0Parameters
Methods
EngquistOsherFluxevaluate_stage1,evaluate_stage2ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsParametricbuild_parameter_type,parse_parameter,strip_parameter
-
class
pymor.operators.fv.L2Product(grid, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between finite volume functions.Parameters
- grid
- The
Gridfor which to assemble the product. - solver_options
- The
solver_optionsfor the operator. - name
- The name of the product.
Methods
-
class
pymor.operators.fv.L2ProductFunctional(grid, function=None, boundary_info=None, dirichlet_data=None, diffusion_function=None, diffusion_constant=None, neumann_data=None, order=1, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorFinite volume functional representing the inner product with an L2-
Function.Additionally, boundary conditions can be enforced by providing
dirichlet_dataandneumann_datafunctions.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product orNone. - boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries orNone. IfNone, no boundary treatment is performed.- dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- diffusion_function
- See
DiffusionOperator. Has to be specified in casedirichlet_datais given. - diffusion_constant
- See
DiffusionOperator. Has to be specified in casedirichlet_datais given. - neumann_data
Functionproviding the Neumann boundary values. IfNone, constant-zero is assumed.- order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
-
class
pymor.operators.fv.LaxFriedrichsFlux(flux, lxf_lambda=1.0)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceLax-Friedrichs numerical flux.
If
fis the analytical flux, the Lax-Friedrichs fluxFis given by:F(U_in, U_out, normal, vol) = vol * [normal⋅(f(U_in) + f(U_out))/2 + (U_in - U_out)/(2*λ)]
Parameters
- flux
Functiondefining the analytical fluxf.- lxf_lambda
- The stabilization parameter
λ.
Methods
LaxFriedrichsFluxevaluate_stage1,evaluate_stage2ImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsParametricbuild_parameter_type,parse_parameter,strip_parameter
-
class
pymor.operators.fv.LinearAdvectionLaxFriedrichs(grid, boundary_info, velocity_field, lxf_lambda=1.0, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection finite Volume
Operatorusing Lax-Friedrichs flux.The operator is of the form
L(u, mu)(x) = ∇ ⋅ (v(x, mu)⋅u(x))
See
LaxFriedrichsFluxfor the definition of the Lax-Friedrichs flux.Parameters
- grid
Gridover which to assemble the operator.- boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries.- velocity_field
Functiondefining the velocity fieldv.- lxf_lambda
- The stabilization parameter
λ. - solver_options
- The
solver_optionsfor the operator. - name
- The name of the operator.
Methods
-
class
pymor.operators.fv.NonlinearAdvectionOperator(grid, boundary_info, numerical_flux, dirichlet_data=None, solver_options=None, space_id='STATE', name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseNonlinear finite volume advection
Operator.The operator is of the form
L(u, mu)(x) = ∇ ⋅ f(u(x), mu)
Parameters
- grid
Gridfor which to evaluate the operator.- boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries.- numerical_flux
- The
NumericalConvectiveFluxto use. - dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- solver_options
- The
solver_optionsfor the operator. - name
- The name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
class
pymor.operators.fv.NonlinearReactionOperator(grid, reaction_function, reaction_function_derivative=None, space_id='STATE', name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseMethods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.operators.fv.NumericalConvectiveFluxInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for numerical convective fluxes for finite volume schemes.
Numerical fluxes defined by this interfaces are functions of the form
F(U_inner, U_outer, unit_outer_normal, edge_volume, mu).- The flux evaluation is vectorized and happens in two stages:
evaluate_stage1receives aNumPy arrayUof all values which appear asU_innerorU_outerfor all edges the flux shall be evaluated at and returns atupleofNumPy arrayseach of the same length asU.evaluate_stage2receives the reorderedstage1_datafor each edge as well as the unit outer normal and the volume of the edges.stage1_datais given as follows: IfR_lisl-th entry of thetuplereturned byevaluate_stage1, thel-th entryD_lof of thestage1_datatuple has the shape(num_edges, 2) + R_l.shape[1:]. If for edgekthe valuesU_innerandU_outerare thei-th andj-th value in theUarray provided toevaluate_stage1, we haveD_l[k, 0] == R_l[i], D_l[k, 1] == R_l[j].
evaluate_stage2returns aNumPy arrayof the flux evaluations for each edge.
Methods
-
class
pymor.operators.fv.ReactionOperator(grid, reaction_coefficient, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorFinite Volume reaction
Operator.The operator is of the form
L(u, mu)(x) = c(x, mu)⋅u(x)
Parameters
- grid
- The
Gridfor which to assemble the operator. - reaction_coefficient
- The function ‘c’
- solver_options
- The
solver_optionsfor the operator. - name
- The name of the operator.
Methods
-
class
pymor.operators.fv.SimplifiedEngquistOsherFlux(flux, flux_derivative)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceEngquist-Osher numerical flux. Simplified Implementation for special case.
For the definition of the Engquist-Osher flux see
EngquistOsherFlux. This class provides a faster and more accurate implementation for the special case thatf(0) == 0and the derivative offonly changes sign at0.Parameters
Methods
-
pymor.operators.fv.nonlinear_advection_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, gausspoints=5, intervals=1, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingEngquistOsherFlux.
-
pymor.operators.fv.nonlinear_advection_lax_friedrichs_operator(grid, boundary_info, flux, lxf_lambda=1.0, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingLaxFriedrichsFlux.
-
pymor.operators.fv.nonlinear_advection_simplified_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingSimplifiedEngquistOsherFlux.
-
class
pymor.operators.interfaces.OperatorInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterdependent discrete operators.An operator in pyMOR is simply a mapping which for any given
Parametermaps vectors from itssourceVectorSpaceto vectors in itsrangeVectorSpace.Note that there is no special distinction between functionals and operators in pyMOR. A functional is simply an operator with
NumpyVectorSpace(1)as itsrangeVectorSpace.Methods
Attributes
-
solver_options¶ If not
None, a dict which can contain the following keys:‘inverse’: solver options used for apply_inverse‘inverse_adjoint’: solver options used for apply_inverse_adjoint‘jacobian’: solver options for the operators returned by jacobian(has no effect for linear operators)If
solver_optionsisNoneor a dict entry is missing orNone, default options are used. The interpretation of the given solver options is up to the operator at hand. In general, values insolver_optionsshould either be strings (indicating a solver type) or dicts of options, usually with an entry'type'which specifies the solver type to use and further items which configure this solver.
-
linear¶ Trueif the operator is linear.
-
source¶ The source
VectorSpace.
-
range¶ The range
VectorSpace.
-
H¶ The adjoint operator, i.e.
self.H.apply(V, mu) == self.apply_adjoint(V, mu)
for all V, mu.
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).If the operator is a linear operator given by multiplication with a matrix M, then
apply2is given as:op.apply2(V, U) = V^T*M*U.
In the case of complex numbers, note that
apply2is anti-linear in the first variable by definition ofdot.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V), len(U))containing the 2-form evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_vector(mu=None, *, space=None)[source]¶ Return a vector representation of a linear functional or vector operator.
Depending on the operator’s
sourceandrange, this method is equivalent to callingas_range_arrayoras_source_arrayrespectively. The resultingVectorArrayis required to have length 1.Note that in case both
sourceandrangeare one-dimensionalNumpyVectorSpacesbut with differentids, it is impossible to determine which space to choose. In this case, the desired space has to be specified via thespaceparameter.Parameters
- mu
- The
Parameterfor which to return the vector representation. - space
- See above.
Returns
- V
VectorArrayof length 1 containing the vector representation.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V),) == (len(U),)containing the 2-form evaluations.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
-
class
pymor.operators.mpi.MPIOperator(obj_id, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]¶ Bases:
pymor.operators.basic.OperatorBaseMPI distributed
Operator.Given a single-rank implementation of an
Operator, this wrapper class uses the event loop frompymor.tools.mpito allow an MPI distributed usage of theOperator.Instances of
MPIOperatorcan be used on rank 0 like any other (non-distributed)Operator.Note, however, that the underlying
Operatorimplementation needs to be MPI aware. For instance, the operator’sapplymethod has to perform the necessary MPI communication to obtain all DOFs hosted on other MPI ranks which are required for the local operator evaluation.Instead of instantiating
MPIOperatordirectly, it is usually preferable to usempi_wrap_operatorinstead.Parameters
- obj_id
ObjectIdof the localOperatorson each rank.- with_apply2
- Set to
Trueif the operator implementation has its own MPI aware implementation ofapply2andpairwise_apply2. Otherwise, the default implementations usingapplyanddotwill be used. - pickle_local_spaces
- If
pickle_local_spacesisFalse, a unique identifier is computed for each local source/rangeVectorSpace, which is then transferred to rank 0 instead of the trueVectorSpace. This allows the useage ofMPIVectorArrayeven when the localVectorSpacesare not picklable. - space_type
- This class will be used to wrap the local
VectorArraysreturned by the local operators into an MPI distributedVectorArraymanaged from rank 0. By default,MPIVectorSpacewill be used, other options areMPIVectorSpaceAutoCommandMPIVectorSpaceNoComm.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).If the operator is a linear operator given by multiplication with a matrix M, then
apply2is given as:op.apply2(V, U) = V^T*M*U.
In the case of complex numbers, note that
apply2is anti-linear in the first variable by definition ofdot.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V), len(U))containing the 2-form evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, mu=None)[source]¶ Treat the operator as a 2-form by computing
V.dot(self.apply(U)).Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- mu
- The
Parameterfor which to evaluate the operator.
Returns
A
NumPy arraywith shape(len(V),) == (len(U),)containing the 2-form evaluations.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).dofs(dofs) == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
pymor.operators.mpi.mpi_wrap_operator(obj_id, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]¶ Wrap MPI distributed local
Operatorsto a globalOperatoron rank 0.Given MPI distributed local
Operatorsreferred to by theObjectIdobj_id, return a newOperatorwhich manages these distributed operators from rank 0. This is done by instantiatingMPIOperator. Additionally, the structure of the wrapped operators is preserved. E.g.LincombOperatorswill be wrapped as aLincombOperatorofMPIOperators.Parameters
See : class:
MPIOperator.Returns
The wrapped
Operator.
This module provides the following NumPy based Operators:
NumpyMatrixOperatorwraps a 2DNumPy arrayas anOperator.NumpyMatrixBasedOperatorshould be used as base class for allOperatorswhich assemble into aNumpyMatrixOperator.NumpyGenericOperatorwraps an arbitrary Python function betweenNumPy arraysas anOperator.
-
class
pymor.operators.numpy.NumpyGenericOperator(mapping, adjoint_mapping=None, dim_source=1, dim_range=1, linear=False, parameter_type=None, source_id=None, range_id=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseWraps an arbitrary Python function between
NumPy arraysas anOperator.Parameters
- mapping
The function to wrap. If
parameter_typeisNone, the function is of the formmapping(U)and is expected to be vectorized. In particular:mapping(U).shape == U.shape[:-1] + (dim_range,).
If
parameter_typeis notNone, the function has to have the signaturemapping(U, mu).- adjoint_mapping
The adjoint function to wrap. If
parameter_typeisNone, the function is of the formadjoint_mapping(U)and is expected to be vectorized. In particular:adjoint_mapping(U).shape == U.shape[:-1] + (dim_source,).
If
parameter_typeis notNone, the function has to have the signatureadjoint_mapping(U, mu).- dim_source
- Dimension of the operator’s source.
- dim_range
- Dimension of the operator’s range.
- linear
- Set to
Trueif the providedmappingandadjoint_mappingare linear. - parameter_type
- The
ParameterTypeof theParametersthe mapping accepts. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
class
pymor.operators.numpy.NumpyMatrixBasedOperator[source]¶ Bases:
pymor.operators.basic.OperatorBaseBase class for operators which assemble into a
NumpyMatrixOperator.Methods
Attributes
-
sparse¶ Trueif the operator assembles into a sparse matrix,Falseif the operator assembles into a dense matrix,Noneif unknown.
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
export_matrix(filename, matrix_name=None, output_format='matlab', mu=None)[source]¶ Save the matrix of the operator to a file.
Parameters
- filename
- Name of output file.
- matrix_name
- The name, the output matrix is given. (Comment field is used in
case of Matrix Market output_format.) If
None, theOperator’snameis used. - output_format
- Output file format. Either
matlabormatrixmarket. - mu
- The
Parameterto assemble the to be exported matrix for.
-
-
class
pymor.operators.numpy.NumpyMatrixOperator(matrix, source_id=None, range_id=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorWraps a 2D
NumPy arrayas anOperator.Parameters
- matrix
- The
NumPy arraywhich is to be wrapped. - source_id
- The id of the operator’s
sourceVectorSpace. - range_id
- The id of the operator’s
rangeVectorSpace. - solver_options
- The
solver_optionsfor the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False, check_finite=True, default_sparse_solver_backend='scipy')[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.- check_finite
- Test if solution only contains finite values.
- default_sparse_solver_backend
- Default sparse solver backend to use (scipy, pyamg, generic).
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
Defaults
check_finite, default_sparse_solver_backend (see
pymor.core.defaults)
-
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - least_squares
If
True, solve the least squares problem:v = argmin ||op^*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
pymor.parallel package¶
Submodules¶
This module contains a base class for implementing WorkerPoolInterface.
-
class
pymor.parallel.basic.RemoteObject(pool, remote_id, uid=None)[source]¶ Bases:
pymor.parallel.interfaces.RemoteObjectInterfaceMethods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved
-
class
pymor.parallel.basic.WorkerPoolBase[source]¶ Bases:
pymor.parallel.basic.WorkerPoolDefaultImplementations,pymor.parallel.interfaces.WorkerPoolInterfaceMethods
Attributes
BasicInterfacelogger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
-
class
pymor.parallel.basic.WorkerPoolDefaultImplementations[source]¶ Bases:
objectMethods
WorkerPoolDefaultImplementationsscatter_array,scatter_list
-
pymor.parallel.default.new_parallel_pool(ipython_num_engines=None, ipython_profile=None, allow_mpi=True)[source]¶ Creates a new default
WorkerPool.If
ipython_num_enginesoripython_profileis provided as an argument or set as adefault, anIPythonPoolWorkerPoolwill be created using the given parameters via theipclusterscript.Otherwise, when
allow_mpiisTrueand an MPI parallel run is detected, anMPIPoolWorkerPoolwill be created.Otherwise, a sequential run is assumed and
pymor.parallel.dummy.dummy_poolis returned.Defaults
ipython_num_engines, ipython_profile, allow_mpi (see
pymor.core.defaults)
-
class
pymor.parallel.dummy.DummyPool[source]¶ Bases:
pymor.parallel.interfaces.WorkerPoolInterfaceMethods
DummyPoolapply,apply_only,map,push,scatter_array,scatter_listBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
scatter_array(U, copy=True)[source]¶ Distribute
VectorArrayevenly among the workers.On each worker a
VectorArrayis created holding an (up to rounding) equal amount of vectors ofU. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- U
- The
VectorArrayto distribute. - copy
- If
False,Uwill be emptied during distribution of the vectors.
Returns
A
RemoteObjectreferring to the scattered data.
-
scatter_list(l)[source]¶ Distribute list of objects evenly among the workers.
On each worker a
listis created holding an (up to rounding) equal amount of objects ofl. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- l
- The list (sequence) of objects to distribute.
Returns
A
RemoteObjectreferring to the scattered data.
-
-
class
pymor.parallel.dummy.DummyRemoteObject(obj)[source]¶ Bases:
pymor.parallel.interfaces.RemoteObjectInterfaceMethods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved
-
class
pymor.parallel.interfaces.RemoteObjectInterface[source]¶ Bases:
objectHandle to remote data on the workers of a
WorkerPool.See documentation of
WorkerPoolInterfacefor usage of these handles in conjunction withapply,scatter_array,scatter_list.Remote objects can be used as a context manager: when leaving the context, the remote object’s
removemethod is called to ensure proper cleanup of remote resources.Methods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved-
remove()[source]¶ Remove the remote object from the workers.
Remove the object this handle refers to from all workers. Note that the object will only be destroyed if no other object on the worker holds a reference to that object. Moreover,
immutableobjects will only be destroyed ifremovehas been called on allRemoteObjectswhich refer to the object (seepush).
-
-
class
pymor.parallel.interfaces.WorkerPoolInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for parallel worker pools.
WorkerPoolsallow to easily parallelize algorithms which involve no or little communication between the workers at runtime. The interface methods give the user simple means to distribute data to workers (push,scatter_array,scatter_list) and execute functions on the distributed data in parallel (apply), collecting the return values from each function call. A single worker can be instructed to execute a function using theWorkerPoolInterface.apply_onlymethod. Finally, a parallelizedmapfunction is available, which automatically scatters the data among the workers.All operations are performed synchronously.
Methods
WorkerPoolInterfaceapply,apply_only,map,push,scatter_array,scatter_list,__len__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
scatter_array(U, copy=True)[source]¶ Distribute
VectorArrayevenly among the workers.On each worker a
VectorArrayis created holding an (up to rounding) equal amount of vectors ofU. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- U
- The
VectorArrayto distribute. - copy
- If
False,Uwill be emptied during distribution of the vectors.
Returns
A
RemoteObjectreferring to the scattered data.
-
scatter_list(l)[source]¶ Distribute list of objects evenly among the workers.
On each worker a
listis created holding an (up to rounding) equal amount of objects ofl. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- l
- The list (sequence) of objects to distribute.
Returns
A
RemoteObjectreferring to the scattered data.
-
-
class
pymor.parallel.ipython.IPythonPool(num_engines=None, **kwargs)[source]¶ Bases:
pymor.parallel.basic.WorkerPoolBaseWorkerPoolbased on the IPython parallel computing features.Parameters
- num_engines
- Number of IPython engines to use. If
None, all available engines are used. - kwargs
- Keyword arguments used to instantiate the IPython cluster client.
Methods
Attributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.parallel.ipython.RemoteId[source]¶ Bases:
intMethods
intbit_length,conjugate,from_bytes,to_bytes,__ceil__,__floor__,__new__,__round__,__sizeof__,__trunc__Attributes
intdenominator,imag,numerator,real
-
class
pymor.parallel.ipython.new_ipcluster_pool(profile=None, cluster_id=None, num_engines=None, ipython_dir=None, min_wait=1, timeout=60)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceCreate a new IPython parallel cluster and connect to it.
This context manager can be used to create an
IPythonPoolWorkerPool. When entering the context a new IPython cluster is created using theipclusterscript and anIPythonPoolis instantiated for the newly created cluster. When leaving the context the cluster is shut down.Parameters
- profile
- Passed as
--profileparameter to theipclusterscript. - cluster_id
- Passed as
--cluster-idparameter to theipclusterscript. - nun_engines
- Passed as
--nparameter to theipclusterscript. - ipython_dir
- Passed as
--ipython-dirparameter to theipclusterscript. - min_wait
- Wait at least this many seconds before trying to connect to the new cluster.
- timeout
- Wait at most this many seconds for all Ipython cluster engines to become available.
Methods
BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.parallel.manager.RemoteObjectManager[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceA simple context manager to keep track of
RemoteObjects.When leaving this context, all
RemoteObjectsthat have beenmanagedby this object will beremoved.Methods
RemoteObjectManagermanage,remove_objectsBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
manage(remote_object)[source]¶ Add a
RemoteObjectto the list of managed objects.Parameters
- remote_object
- The object to add to the list.
Returns
remote_object
-
-
class
pymor.parallel.mpi.MPIPool[source]¶ Bases:
pymor.parallel.basic.WorkerPoolBaseWorkerPoolbased pyMOR’s MPIevent loop.Methods
Attributes
BasicInterfacelogger,logging_disabled,name,uid
pymor.parameters package¶
Submodules¶
This module contains the implementation of pyMOR’s parameter handling facilities.
A Parameter in pyMOR is basically a dict of NumPy arrays. Each item of the
dict is called a parameter component. The ParameterType of a Parameter is the dict
of the shapes of the parameter components, i.e.
mu.parameter_type['component'] == mu['component'].shape
Classes which represent mathematical objects depending on parameters, e.g. Functions,
Operators, Discretizations derive from the Parametric mixin. Each Parametric
object has a parameter_type attribute holding the ParameterType
of the Parameters the object’s evaluate, apply, solve, etc. methods expect.
Note that the ParameterType of the given Parameter is allowed to be a
superset of the object’s ParameterType.
The ParameterType of a Parametric object is determined in its __init__
method by calling build_parameter_type which computes the
ParameterType as the union of the ParameterTypes of the objects given to the
method. This way, e.g., an Operator can inherit the ParameterTypes of the
data functions it depends upon.
A Parametric object can have a ParameterSpace assigned to it by setting the
parameter_space attribute (the ParameterType of the space
has to agree with the ParameterType of the object). The
parse_parameter method parses a user input according to
the object’s ParameterType to make it a Parameter (e.g. if the ParameterType
consists of a single one-dimensional component, the user can simply supply a list
of numbers of the right length). Moreover, when given a Parameter,
parse_parameter ensures the Parameter has an appropriate
ParameterType.
-
class
pymor.parameters.base.Parameter(v)[source]¶ Bases:
dictClass representing a parameter.
A
Parameteris simply adictwhere each key is a string and each value is aNumPy array. We call an item of the dictionary a parameter component.A
Parameterdiffers from an ordinarydictin the following ways:- It is ensured that each value is a
NumPy array. - We overwrite
copyto ensure that not only thedictbut also theNumPy arraysare copied. - The
allclosemethod allows to compareParametersfor equality in a mathematically meaningful way. - Each
Parameterhas asidproperty providing a unique state id. - We override
__str__to ensure alphanumerical ordering of the keys and pretty printing of the values. - The
parameter_typeproperty can be used to obtain theParameterTypeof the parameter. - Use
from_parameter_typeto construct aParameterfrom aParameterTypeand user supplied input.
Parameters
- v
- Anything that
dictaccepts for the construction of a dictionary.
Methods
Parameterallclose,clear,copy,from_parameter_type,fromkeys,pop,popitem,updatedictget,items,keys,setdefault,values,__contains__,__getitem__,__new__,__sizeof__Attributes
Parameterparameter_type,sid-
parameter_type¶ The
ParameterTypeof theParameter.
-
allclose(mu)[source]¶ Compare two
Parametersusingfloat_cmp_all.Parameters
- mu
- The
Parameterwith which to compare.
Returns
Trueif bothParametershave the sameParameterTypeand all parameter components are almost equal, elseFalse.
-
classmethod
from_parameter_type(mu, parameter_type=None)[source]¶ Takes a user input
muand interprets it as aParameteraccording to the givenParameterType.Depending on the
ParameterType,mucan be given as aParameter, dict, tuple, list, array or scalar.Parameters
- mu
- The user input which shall be interpreted as a
Parameter. - parameter_type
- The
ParameterTypew.r.t. whichmuis to be interpreted.
Returns
The resulting
Parameter.Raises
- ValueError
- Is raised if
mucannot be interpreted as aParameterofParameterTypeparameter_type.
-
fromkeys(S, v=None)[source]¶ Create a new dictionary with keys from iterable and values set to value.
-
pop(k[, d]) → v, remove specified key and return the corresponding value.[source]¶ If key is not found, d is returned if given, otherwise KeyError is raised
- It is ensured that each value is a
-
class
pymor.parameters.base.ParameterType(t)[source]¶ Bases:
collections.OrderedDictClass representing a parameter type.
A parameter type is simply a dictionary with strings as keys and tuples of natural numbers as values. The keys are the names of the parameter components and the tuples their expected shape (compare
Parameter).Apart from checking the correct format of its values, the only difference between a
ParameterTypeand an ordinarydictis, thatParameterTypeorders its keys alphabetically.Parameters
- t
- If
tis an object with aparameter_typeattribute, a copy of thisParameterTypeis created. Otherwise,tcan be anything from which adictcan be constructed.
Methods
ParameterTypecopy,fromkeysOrderedDictclear,items,keys,move_to_end,pop,popitem,setdefault,update,values,__reversed__dictget,__contains__,__getitem__,__new__Attributes
ParameterTypesid
-
class
pymor.parameters.base.Parametric[source]¶ Bases:
objectMixin class for objects representing mathematical entities depending on a
Parameter.Each such object has a
ParameterTypestored in theparameter_typeattribute, which should be set by the implementor during__init__using thebuild_parameter_typemethod. Methods expecting theParameter(typicallyevaluate,apply,solve, etc. ..) should accept an optional argumentmudefaulting toNone. This argumentmushould then be fed intoparse_parameterto obtain aParameterof correctParameterTypefrom the (user supplied) inputmu.Attributes
Parametricparameter_space,parameter_type,parametric-
parameter_type¶ The
ParameterTypeof theParametersthe object expects.
-
parameter_space¶ ParameterSpacethe parameters are expected to lie in orNone.
-
parametric¶ Trueif the object really depends on a parameter, i.e.parameter_typeis not empty.
-
build_parameter_type(*args, provides=None, **kwargs)[source]¶ Builds the
ParameterTypeof the object. Should be called by__init__.The
ParameterTypeof aParametricobject is determined by the parameter components the object itself requires for evaluation, and by the parameter components required by the objects the object depends upon for evaluation.All parameter components (directly specified or inherited by the
ParameterTypeof a givenParametricobject) with the same name are treated as identical and are thus required to have the same shapes. The object’sParameterTypeis then made up by the shapes of all parameter components appearing.Additionally components of the resulting
ParameterTypecan be removed by specifying them via theprovidesparameter. The idea is that the object itself may provide parameter components to the inherited objects which thus should not become part of the object’s own parameter type. (A typical application would beInstationaryDiscretization, which provides a time parameter component to its (time-dependent) operators during time-stepping.)Parameters
- args
- Each positional argument must either be a dict of parameter components and shapes or
a
Parametricobject whoseparameter_typeis added. - kwargs
- Each keyword argument is interpreted as parameter component with corresponding shape.
- provides
Dictof parameter component names and shapes which are provided by the object itself. The parameter components listed here will not become part of the object’sParameterType.
-
parse_parameter(mu)[source]¶ Interpret a user supplied parameter
muas aParameter.If
muis not already aParameter,Parameter.from_parameter_typeis used, to makemua parameter of the correctParameterType. Ifmuis already aParameter, it is checked if itsParameterTypematches our own. (It is actually allowed that theParameterTypeofmuis a superset of our ownParameterTypein the obvious sense.)Parameters
- mu
- The input to parse as a
Parameter.
-
strip_parameter(mu)[source]¶ Remove all components of the
Parametermuwhich are not part of the object’sParameterType.Otherwise
strip_parameterbehaves likeparse_parameter.This method is mainly useful for caching where the key should only contain the relevant parameter components.
-
-
class
pymor.parameters.functionals.ExpressionParameterFunctional(expression, parameter_type, name=None)[source]¶ Bases:
pymor.parameters.functionals.GenericParameterFunctionalTurns a Python expression given as a string into a
ParameterFunctional.Some
NumPyarithmetic functions likesin,log,minare supported. For a full list see thefunctionsclass attribute.Warning
evalis used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!Parameters
- expression
- A Python expression in the parameter components of the given
parameter_type. - parameter_type
- The
ParameterTypeof theParametersthe functional expects. - name
- The name of the functional.
Methods
-
class
pymor.parameters.functionals.GenericParameterFunctional(mapping, parameter_type, name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceA wrapper making an arbitrary Python function a
ParameterFunctionalNote that a GenericParameterFunctional can only be
pickledif the function it is wrapping can be pickled. For this reason, it is usually preferable to useExpressionParameterFunctionalinstead ofGenericParameterFunctional.Parameters
- mapping
- The function to wrap. The function has signature
mapping(mu). - parameter_type
- The
ParameterTypeof theParametersthe functional expects. - name
- The name of the functional.
Methods
-
class
pymor.parameters.functionals.ProductParameterFunctional(factors, name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceForms the product of a list of
ParameterFunctionalsor numbers.Parameters
- factors
- A list of
ParameterFunctionalsor numbers. - name
- Name of the functional.
Methods
-
class
pymor.parameters.functionals.ProjectionParameterFunctional(component_name, component_shape, coordinates=(), name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceParameterFunctionalreturning a component of the given parameter.For given parameter
mu, this functional evaluates tomu[component_name][coordinates]
Parameters
- component_name
- The name of the parameter component to return.
- component_shape
- The shape of the parameter component.
- coordinates
- See above.
- name
- Name of the functional.
Methods
-
class
pymor.parameters.interfaces.ParameterFunctionalInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterfunctionals.A parameter functional is simply a function mapping a
Parameterto a number.Methods
-
class
pymor.parameters.interfaces.ParameterSpaceInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInterface for
Parameterspaces.Methods
ParameterSpaceInterfacecontainsImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ParameterSpaceInterfaceparameter_typeImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
parameter_type¶ ParameterTypeof the space.
-
-
class
pymor.parameters.spaces.CubicParameterSpace(parameter_type, minimum=None, maximum=None, ranges=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterSpaceInterfaceSimple
ParameterSpacewhere each summand is an n-cube.Parameters
- parameter_type
- The
ParameterTypeof the space. - minimum
- The minimum for each matrix entry of each
Parametercomponent. Must beNoneifrangesis specified. - maximum
- The maximum for each matrix entry of each
Parametercomponent. Must beNoneifrangesis specified. - ranges
- dict whose keys agree with
parameter_typeand whose values are tuples (min, max) specifying the minimum and maximum of each matrix entry of correspondingParametercomponent. Must beNoneifminimumandmaximumare specified.
Methods
Attributes
ParameterSpaceInterfaceparameter_typeImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
sample_randomly(count=None, random_state=None, seed=None)[source]¶ Randomly sample
Parametersfrom the space.Warning
When neither
random_statenorseedare specified, repeated calls to this method will return the same sequence of parameters!Parameters
- count
Noneor number of random parameters (see below).- random_state
RandomStateto use for sampling. IfNone, a new random state is generated usingseedas random seed.- seed
- Random seed to use. If
None, thedefaultrandom seed is used.
Returns
If
countisNone, an inexhaustible iterator returning randomParameters. Otherwise a list ofcountrandomParameters.
-
sample_uniformly(counts)[source]¶ Uniformly sample
Parametersfrom the space.
pymor.playground package¶
Subpackages¶
-
class
pymor.playground.core.network_cache.NetworkFilesystemRegion(server_path, secret='')[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
NetworkFilesystemRegionclear,get,setAttributes
NetworkFilesystemRegionpersistent
-
class
pymor.playground.core.network_cache.NetworkFilesystemRegionServer(addr, path, secret=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceMethods
NetworkFilesystemRegionServerserve_foreverBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
pymor.playground.discretizers.numpylistvectorarray.convert_to_numpy_list_vector_array(d)[source]¶ Use NumpyListVectorArrayMatrixOperator instead of NumpyMatrixOperator.
This simple function converts linear, affinely decomposed discretizations to use
NumpyListVectorArrayMatrixOperatorinstead ofNumpyMatrixOperator.
-
class
pymor.playground.functions.expression_function.ExpressionFunction(expressions, variables='x y z')[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceMethods
BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.playground.operators.numpy.NumpyListVectorArrayMatrixOperator(matrix, source_id=None, range_id=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixOperatorVariant of
NumpyMatrixOperatorusingListVectorArrayinstead ofNumpyVectorArray.Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(V, mu=None)[source]¶ Apply the adjoint operator.
For any given linear
Operatorop,ParametermuandVectorArraysU,Vin thesourceresp.rangewe have:op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))
Thus, when
opis represented by a matrixM,apply_adjointis given by left-multplication of (the complex conjugate of)MwithV.Parameters
- V
VectorArrayof vectors to which the adjoint operator is applied.- mu
- The
Parameterfor which to apply the adjoint operator.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.- check_finite
- Test if solution only contains finite values.
- default_sparse_solver_backend
- Default sparse solver backend to use (scipy, pyamg, generic).
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
Defaults
check_finite, default_sparse_solver_backend (see
pymor.core.defaults)
-
as_range_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its range space.In the case of a linear operator with
NumpyVectorSpaceassource, this method returns for everyParametermuaVectorArrayVin the operator’srange, such thatV.lincomb(U.to_numpy()) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
as_source_array(mu=None)[source]¶ Return a
VectorArrayrepresentation of the operator in its source space.In the case of a linear operator with
NumpyVectorSpaceasrange, this method returns for everyParametermuaVectorArrayVin the operator’ssource, such thatself.range.make_array(V.dot(U).T) == self.apply(U, mu)
for all
VectorArraysU.Parameters
- mu
- The
Parameterfor which to return theVectorArrayrepresentation.
Returns
- V
- The
VectorArraydefined above.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
pymor.reductors package¶
Submodules¶
-
class
pymor.reductors.basic.GenericPGReductor(d, W, V, bases_are_biorthonormal, vector_ranged_operators=('initial_data', ), product=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric Petrov-Galerkin reductor.
Replaces each
Operatorof the givenDiscretizationwith the projection onto the span of the given projection matrices.Parameters
- d
- The
Discretizationwhich is to be reduced. - W
VectorArraycontaining the left projection matrix.- V
VectorArraycontaining the right projection matrix.- bases_are_biorthonormal
- Indicate whether or not V and W are biorthonormal w.r.t.
product. - vector_ranged_operators
- List of keys in
d.operatorsfor which the correspondingOperatorshould be biorthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals). - product
- Inner product for the projection of the
Operatorsgiven byvector_ranged_operators.
Methods
GenericPGReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce()[source]¶ Perform the Petrov-Galerkin projection.
Returns
The reduced
Discretization.
-
class
pymor.reductors.basic.GenericRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric reduced basis reductor.
Replaces each
Operatorof the givenDiscretizationwith the Galerkin projection onto the span of the given reduced basis.Parameters
- d
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- basis_is_orthonormal
- If
RBis specified, indicate whether or not the basis is orthonormal w.r.t.product. - vector_ranged_operators
- List of keys in
d.operatorsfor which the correspondingOperatorshould be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals). - product
- Inner product for the orthonormalization of
RBand the projection of theOperatorsgiven byvector_ranged_operators.
Methods
GenericRBReductorextend_basis,reconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
extend_basis(U, method='gram_schmidt', pod_modes=1, pod_orthonormalize=True, orthonormal=None, copy_U=True)[source]¶ Extend basis by new vectors.
Parameters
- U
VectorArraycontaining the new basis vectors.- method
Basis extension method to use. The following methods are available:
trivial: Vectors in Uare appended to the basis. Duplicate vectors in the sense ofalmost_equalare removed.gram_schmidt: New basis vectors are orthonormalized w.r.t. to the old basis using the gram_schmidtalgorithm.pod: Append the first POD modes of the defects of the projections of the vectors in U onto the existing basis (e.g. for use in POD-Greedy algorithm). Warning
In case of the
'gram_schmidt'and'pod'extension methods, the existing reduced basis is assumed to be orthonormal w.r.t. the given inner product.- pod_modes
- In case
method == 'pod', the number of POD modes that shall be appended to the basis. - pod_orthonormalize
- If
Trueandmethod == 'pod', re-orthonormalize the new basis vectors obtained by the POD in order to improve numerical accuracy. - orthonormal
- If
method == 'trivial', set this toTrueto indicate that the basis will remain orthonormal after extending. - copy_U
- If
copy_UisFalse, the new basis vectors might be removed fromU.
Raises
- ExtensionError
- Raised when the selected extension method does not yield a basis of increased dimension.
-
reduce(dim=None)[source]¶ Perform the reduced basis projection.
Parameters
- dim
- If specified, the desired reduced state dimension. Must not be larger than the current reduced basis dimension.
Returns
The reduced
Discretization.
-
class
pymor.reductors.bt.BRBTReductor(d, gamma, solver_options=None)[source]¶ Bases:
pymor.reductors.bt.GenericBTReductorBounded Real (BR) Balanced Truncation reductor.
See [A05] (Section 7.5.3) and [OJ88].
Parameters
- d
- The system which is to be reduced.
- gamma
- Upper bound for the
-norm. - solver_options
- The solver options to use to solve the positive Riccati equations.
Methods
BRBTReductorerror_bounds,gramiansGenericBTReductorreconstruct,reduce,sv_U_VBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.bt.BTReductor(d)[source]¶ Bases:
pymor.reductors.bt.GenericBTReductorStandard (Lyapunov) Balanced Truncation reductor.
See Section 7.3 in [A05].
Parameters
- d
- The system which is to be reduced.
Methods
BTReductorerror_bounds,gramiansGenericBTReductorreconstruct,reduce,sv_U_VBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.bt.GenericBTReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric Balanced Truncation reductor.
Parameters
- d
- The system which is to be reduced.
Methods
GenericBTReductorerror_bounds,gramians,reconstruct,reduce,sv_U_VBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r=None, tol=None, projection='bfsr')[source]¶ Generic Balanced Truncation.
Parameters
- r
- Order of the reduced model if
tolisNone, maximum order iftolis specified. - tol
- Tolerance for the error bound if
risNone. - projection
Projection method used:
'sr': square root method'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices (usinggram_schmidt_biorth)
Returns
- rd
- Reduced system.
-
class
pymor.reductors.bt.LQGBTReductor(d, solver_options=None)[source]¶ Bases:
pymor.reductors.bt.GenericBTReductorLinear Quadratic Gaussian (LQG) Balanced Truncation reductor.
See Section 3 in [MG91].
Parameters
- d
- The system which is to be reduced.
- solver_options
- The solver options to use to solve the Riccati equations.
Methods
LQGBTReductorerror_bounds,gramiansGenericBTReductorreconstruct,reduce,sv_U_VBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.coercive.CoerciveRBEstimator(residual, residual_range_dims, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
CoerciveRBReductor.Not to be used directly.
Methods
CoerciveRBEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors
-
class
pymor.reductors.coercive.CoerciveRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None, coercivity_estimator=None)[source]¶ Bases:
pymor.reductors.basic.GenericRBReductorReduced Basis reductor for
StationaryDiscretizationswith coercive linear operator.The only addition to
GenericRBReductoris an error estimator which evaluates the dual norm of the residual with respect to a given inner product. For the reduction of the residual we useResidualReductorfor improved numerical stability [BEOR14].Parameters
- d
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- basis_is_orthonormal
- If
RBis specified, indicate whether or not the basis is orthonormal w.r.t.product. - vector_ranged_operators
- List of keys in
d.operatorsfor which the correspondingOperatorshould be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals). - product
- Inner product for the orthonormalization of
RB, the projection of theOperatorsgiven byvector_ranged_operatorsand for the computation of Riesz representatives of the residual. IfNone, the Euclidean product is used. - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.
Methods
GenericRBReductorextend_basis,reconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.coercive.SimpleCoerciveRBEstimator(estimator_matrix, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
SimpleCoerciveRBReductor.Not to be used directly.
Methods
SimpleCoerciveRBEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors
-
class
pymor.reductors.coercive.SimpleCoerciveRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None, coercivity_estimator=None)[source]¶ Bases:
pymor.reductors.basic.GenericRBReductorReductor for linear
StationaryDiscretizationswith affinely decomposed operator and rhs.Note
The reductor
CoerciveRBReductorcan be used for arbitrary coerciveStationaryDiscretizationsand offers an improved error estimator with better numerical stability.The only addition is to
GenericRBReductoris an error estimator, which evaluates the norm of the residual with respect to a given inner product.Parameters
- d
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- basis_is_orthonormal
- If
RBis specified, indicate whether or not the basis is orthonormal w.r.t.product. - vector_ranged_operators
- List of keys in
d.operatorsfor which the correspondingOperatorshould be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals). - product
- Inner product for the orthonormalization of
RB, the projection of theOperatorsgiven byvector_ranged_operatorsand for the computation of Riesz representatives of the residual. IfNone, the Euclidean product is used. - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.
Methods
GenericRBReductorextend_basis,reconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.h2.IRKAReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceIterative Rational Krylov Algorithm reductor.
Parameters
- d
LTISystem.
Methods
IRKAReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, projection='orth', use_arnoldi=False, conv_crit='sigma', compute_errors=False)[source]¶ Reduce using IRKA.
See [GAB08] (Algorithm 4.1) and [ABG10] (Algorithm 1).
Parameters
- r
- Order of the reduced order model.
- sigma
Initial interpolation points (closed under conjugation).
If
None, interpolation points are log-spaced between 0.1 and 10. Ifsigmais anint, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of lengthr.sigmaandrd0cannot both be notNone.- b
Initial right tangential directions.
If
None, if is chosen as all ones. Ifbis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aVectorArrayof lengthrfromd.B.source.bandrd0cannot both be notNone.- c
Initial left tangential directions.
If
None, if is chosen as all ones. Ifcis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aVectorArrayof lengthrfromd.C.range.candrd0cannot both be notNone.- rd0
Initial reduced order model.
If
None, thensigma,b, andcare used. Otherwise, it needs to be anLTISystemof orderrand it is used to constructsigma,b, andc.- tol
- Tolerance for the convergence criterion.
- maxit
- Maximum number of iterations.
- num_prev
- Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of IRKA.
- force_sigma_in_rhp
- If
False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only poles in the left half-plane are reflected. - projection
Projection method:
'orth': projection matrices are orthogonalized with respect to the Euclidean inner product'biorth': projection matrices are biorthogolized with respect to the E product
- use_arnoldi
- Should the Arnoldi process be used for rational interpolation. Available only for SISO systems. Otherwise, it is ignored.
- conv_crit
Convergence criterion:
'sigma': relative change in interpolation points'h2': relative
distance of
reduced-order models
- compute_errors
Should the relative
-errors of
intermediate reduced order models be computed.Warning
Computing
-errors is expensive. Use
this option only if necessary.
Returns
- rd
- Reduced
LTISystemmodel.
-
class
pymor.reductors.h2.TF_IRKAReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceRealization-independent IRKA reductor.
See [BG12].
Parameters
- d
- Discretization with
eval_tfandeval_dtfmethods.
Methods
TF_IRKAReductorreduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, conv_crit='sigma')[source]¶ Reduce using TF-IRKA.
Parameters
- r
- Order of the reduced order model.
- sigma
Initial interpolation points (closed under conjugation).
If
None, interpolation points are log-spaced between 0.1 and 10. Ifsigmais anint, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of lengthr.sigmaandrd0cannot both be notNone.- b
Initial right tangential directions.
If
None, if is chosen as all ones. Ifbis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aNumPy arrayof shape(m, r).bandrd0cannot both be notNone.- c
Initial left tangential directions.
If
None, if is chosen as all ones. Ifcis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aNumPy arrayof shape(p, r).candrd0cannot both be notNone.- rd0
Initial reduced order model.
If
None, thensigma,b, andcare used. Otherwise, it needs to be anLTISystemof orderrand it is used to constructsigma,b, andc.- tol
- Tolerance for the convergence criterion.
- maxit
- Maximum number of iterations.
- num_prev
- Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of TF-IRKA.
- force_sigma_in_rhp
- If
False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only the poles in the left half-plane are reflected. - conv_crit
Convergence criterion:
'sigma': relative change in interpolation points'h2': relative
distance of
reduced-order models
Returns
- rd
- Reduced
LTISystemmodel.
-
class
pymor.reductors.h2.TSIAReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceTwo-Sided Iteration Algorithm reductor.
Parameters
- d
LTISystem.
Methods
TSIAReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(rd0, tol=0.0001, maxit=100, num_prev=1, projection='orth', conv_crit='sigma', compute_errors=False)[source]¶ Reduce using TSIA.
See [XZ11] (Algorithm 1) and [BKS11].
In exact arithmetic, TSIA is equivalent to IRKA (under some assumptions on the poles of the reduced model). The main difference in implementation is that TSIA computes the Schur decomposition of the reduced matrices, while IRKA computes the eigenvalue decomposition. Therefore, TSIA might behave better for non-normal reduced matrices.
Parameters
- rd0
- Initial reduced order model.
- tol
- Tolerance for the convergence criterion.
- maxit
- Maximum number of iterations.
- num_prev
- Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of TSIA.
- projection
Projection method:
'orth': projection matrices are orthogonalized with respect to the Euclidean inner product'biorth': projection matrices are biorthogolized with respect to the E product
- conv_crit
Convergence criterion:
'sigma': relative change in interpolation points'h2': relative
distance of
reduced-order models
- compute_errors
Should the relative
-errors of
intermediate reduced order models be computed.Warning
Computing
-errors is expensive. Use
this option only if necessary.
Returns
- rd
- Reduced
LTISystem.
-
pymor.reductors.h2._convergence_criterion(data, conv_crit)[source]¶ Compute the convergence criterion for given data.
-
class
pymor.reductors.interpolation.GenericBHIReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric bitangential Hermite interpolation reductor.
This is a generic reductor for reducing any linear
InputStateOutputSystemwith the transfer function which can be written in the generalized coprime factorization
as in [BG09].
The interpolation here is limited to only up to the first
derivative.
Hence, interpolation points are assumed to be pairwise distinct.Parameters
- d
- Discretization.
Methods
GenericBHIReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(sigma, b, c, projection='orth')[source]¶ Bitangential Hermite interpolation.
Parameters
- sigma
- Interpolation points (closed under conjugation), list of
length
r. - b
- Right tangential directions,
VectorArrayof lengthrfromself.d.input_space. - c
- Left tangential directions,
VectorArrayof lengthrfromself.d.output_space. - projection
Projection method:
'orth': projection matrices are orthogonalized with respect to the Euclidean inner product'biorth': projection matrices are biorthogolized with respect to the E product
Returns
- rd
- Reduced discretization.
-
class
pymor.reductors.interpolation.LTI_BHIReductor(d)[source]¶ Bases:
pymor.reductors.interpolation.GenericBHIReductorBitangential Hermite interpolation for
LTISystems.Parameters
- d
LTISystem.
Methods
LTI_BHIReductorreduce,reduce_arnoldiGenericBHIReductorreconstructBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(sigma, b, c, projection='orth', use_arnoldi=False)[source]¶ Bitangential Hermite interpolation.
Parameters
- sigma
- Interpolation points (closed under conjugation), list of
length
r. - b
- Right tangential directions,
VectorArrayof lengthrfromself.d.input_space. - c
- Left tangential directions,
VectorArrayof lengthrfromself.d.output_space. - projection
Projection method:
'orth': projection matrices are orthogonalized with respect to the Euclidean inner product'biorth': projection matrices are biorthogolized with respect to the E product
- use_arnoldi
- Should the Arnoldi process be used for rational interpolation. Available only for SISO systems. Otherwise, it is ignored.
Returns
- rd
- Reduced discretization.
-
reduce_arnoldi(sigma, b, c)[source]¶ Bitangential Hermite interpolation for SISO
LTISystems.Parameters
- sigma
- Interpolation points (closed under conjugation), list of
length
r. - b
- Right tangential directions,
VectorArrayof lengthrfromself.d.B.source. - c
- Left tangential directions,
VectorArrayof lengthrfromself.d.C.range.
Returns
- rd
- Reduced
LTISystemmodel.
-
class
pymor.reductors.interpolation.SO_BHIReductor(d)[source]¶ Bases:
pymor.reductors.interpolation.GenericBHIReductorBitangential Hermite interpolation for second-order systems.
Parameters
Methods
GenericBHIReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.interpolation.TFInterpReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceLoewner bitangential Hermite interpolation reductor.
See [BG12].
Parameters
- d
- Discretization with
eval_tfandeval_dtfmethods.
Methods
TFInterpReductorreduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(sigma, b, c)[source]¶ Realization-independent tangential Hermite interpolation.
Parameters
- sigma
- Interpolation points (closed under conjugation), list of
length
r. - b
- Right tangential directions,
NumPy arrayof shape(d.m, r). - c
- Left tangential directions,
NumPy arrayof shape(d.p, r).
Returns
- lti
LTISysteminterpolating the transfer function ofd.
-
class
pymor.reductors.parabolic.ParabolicRBEstimator(residual, residual_range_dims, initial_residual, initial_residual_range_dims, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
ParabolicRBReductor.Not to be used directly.
Methods
ParabolicRBEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors
-
class
pymor.reductors.parabolic.ParabolicRBReductor(d, RB=None, basis_is_orthonormal=None, product=None, coercivity_estimator=None)[source]¶ Bases:
pymor.reductors.basic.GenericRBReductorReduced Basis Reductor for parabolic equations.
This reductor uses
GenericRBReductorfor the actual RB-projection. The only addition is the assembly of an error estimator which bounds the discrete l2-in time / energy-in space error similar to [GP05], [HO08] as follows:![\left[ C_a^{-1}(\mu)\|e_N(\mu)\|^2 + \sum_{n=1}^{N} \Delta t\|e_n(\mu)\|^2_e \right]^{1/2}
\leq \left[ C_a^{-1}(\mu)\Delta t \sum_{n=1}^{N}\|\mathcal{R}^n(u_n(\mu), \mu)\|^2_{e,-1}
+ C_a^{-1}(\mu)\|e_0\|^2 \right]^{1/2}](_images/math/f85904507cddb59d98fd4c592d4602b1207b449f.png)
Here,
denotes the norm induced by the problem’s mass matrix
(e.g. the L^2-norm) and
is an arbitrary energy norm w.r.t.
which the space operator
is coercive, and
is a
lower bound for its coercivity constant. Finally,
denotes
the implicit Euler timestepping residual for the (fixed) time step size
,
where
denotes the mass operator and
the source term.
The dual norm of the residual is computed using the numerically stable projection
from [BEOR14].Parameters
- d
- The
InstationaryDiscretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- basis_is_orthonormal
- Indicate whether or not the basis is orthonormal w.r.t.
product. - product
- The energy inner product
Operatorw.r.t. which the reduction error is estimated andRBis orthonormalized. - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound
for the coercivity constant of d.operatorw.r.t.product.
Methods
GenericRBReductorextend_basis,reconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.residual.ImplicitEulerResidualOperator(operator, mass, rhs, dt, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseInstantiated by
ImplicitEulerResidualReductor.Methods
Attributes
-
apply(U, U_old, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.ImplicitEulerResidualReductor(RB, operator, mass, dt, rhs=None, product=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceReduced basis residual reductor with mass operator for implicit Euler timestepping.
Given an operator, mass and a functional, the concatenation of residual operator with the Riesz isomorphism is given by:
riesz_residual.apply(U, U_old, mu) == product.apply_inverse(operator.apply(U, mu) + 1/dt*mass.apply(U, mu) - 1/dt*mass.apply(U_old, mu) - rhs.as_vector(mu))
This reductor determines a low-dimensional subspace of the image of a reduced basis space under
riesz_residualusingestimate_image_hierarchical, computes an orthonormal basisresidual_rangeof this range space and then returns the Petrov-Galerkin projectionprojected_riesz_residual == riesz_residual.projected(range_basis=residual_range, source_basis=RB)
of the
riesz_residualoperator. Given reduced basis coefficient vectorsuandu_old, the dual norm of the residual can then be computed asprojected_riesz_residual.apply(u, u_old, mu).l2_norm()
Moreover, a
reconstructmethod is provided such thatresidual_reductor.reconstruct(projected_riesz_residual.apply(u, u_old, mu)) == riesz_residual.apply(RB.lincomb(u), RB.lincomb(u_old), mu)
Parameters
- operator
- See definition of
riesz_residual. - mass
- The mass operator. See definition of
riesz_residual. - dt
- The time step size. See definition of
riesz_residual. - rhs
- See definition of
riesz_residual. IfNone, zero right-hand side is assumed. - RB
VectorArraycontaining a basis of the reduced space onto which to project.- product
- Inner product
Operatorw.r.t. which to compute the Riesz representatives.
Methods
ImplicitEulerResidualReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.residual.NonProjectedImplicitEulerResidualOperator(operator, mass, rhs, dt, product)[source]¶ Bases:
pymor.reductors.residual.ImplicitEulerResidualOperatorInstantiated by
ImplicitEulerResidualReductor.Not to be used directly.
Methods
Attributes
-
apply(U, U_old, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.NonProjectedResidualOperator(operator, rhs, riesz_representatives, product)[source]¶ Bases:
pymor.reductors.residual.ResidualOperatorInstantiated by
ResidualReductor.Not to be used directly.
Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.ResidualOperator(operator, rhs, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseInstantiated by
ResidualReductor.Methods
Attributes
-
apply(U, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.ResidualReductor(RB, operator, rhs=None, product=None, riesz_representatives=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric reduced basis residual reductor.
Given an operator and a right-hand side, the residual is given by:
residual.apply(U, mu) == operator.apply(U, mu) - rhs.as_range_array(mu)
When operator maps to functionals instead of vectors, we are interested in the Riesz representative of the residual:
residual.apply(U, mu) == product.apply_inverse(operator.apply(U, mu) - rhs.as_range_array(mu))
Given a basis
RBof a subspace of the source space ofoperator, this reductor usesestimate_image_hierarchicalto determine a low-dimensional subspace containing the image of the subspace underresidual(resp.riesz_residual), computes an orthonormal basisresidual_rangefor this range space and then returns the Petrov-Galerkin projectionprojected_residual == project(residual, range_basis=residual_range, source_basis=RB)
of the residual operator. Given a reduced basis coefficient vector
u, w.r.t.RB, the (dual) norm of the residual can then be computed asprojected_residual.apply(u, mu).l2_norm()
Moreover, a
reconstructmethod is provided such thatresidual_reductor.reconstruct(projected_residual.apply(u, mu)) == residual.apply(RB.lincomb(u), mu)
Parameters
- RB
VectorArraycontaining a basis of the reduced space onto which to project.- operator
- See definition of
residual. - rhs
- See definition of
residual. IfNone, zero right-hand side is assumed. - product
- Inner product
Operatorw.r.t. which to orthonormalize and w.r.t. which to compute the Riesz representatives in caseoperatormaps to functionals. - riesz_representatives
- If
Truecompute the Riesz representative of the residual.
Methods
ResidualReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.sobt.GenericSOBTpvReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceGeneric Second-Order Balanced Truncation position/velocity reductor.
See [RS08].
Parameters
- d
- The system which is to be reduced.
Methods
GenericSOBTpvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, projection='bfsr')[source]¶ Reduce using GenericSOBTpv.
Parameters
- r
- Order of the reduced model.
- projection
Projection method used:
'sr': square root method'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices
Returns
- rd
- Reduced system.
-
class
pymor.reductors.sobt.SOBTReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceSecond-Order Balanced Truncation reductor.
See [CLVV06].
Parameters
- d
- The system which is to be reduced.
Methods
SOBTReductorreduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, projection='bfsr')[source]¶ Reduce using SOBT.
Parameters
- r
- Order of the reduced model.
- projection
Projection method used:
'sr': square root method'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices
Returns
- rd
- Reduced system.
-
class
pymor.reductors.sobt.SOBTfvReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceFree-velocity Second-Order Balanced Truncation reductor.
See [MS96].
Parameters
- d
- The system which is to be reduced.
Methods
SOBTfvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, projection='bfsr')[source]¶ Reduce using SOBTfv.
Parameters
- r
- Order of the reduced model.
- projection
Projection method used:
'sr': square root method'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices
Returns
- rd
- Reduced system.
-
class
pymor.reductors.sobt.SOBTpReductor(d)[source]¶ Bases:
pymor.reductors.sobt.GenericSOBTpvReductorSecond-Order Balanced Truncation position reductor.
See [RS08].
Parameters
- d
- The system which is to be reduced.
Methods
GenericSOBTpvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.sobt.SOBTpvReductor(d)[source]¶ Bases:
pymor.reductors.sobt.GenericSOBTpvReductorSecond-Order Balanced Truncation position-velocity reductor.
See [RS08].
Parameters
- d
- The system which is to be reduced.
Methods
GenericSOBTpvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.sobt.SOBTvReductor(d)[source]¶ Bases:
pymor.reductors.sobt.GenericSOBTpvReductorSecond-Order Balanced Truncation velocity reductor.
See [RS08].
Parameters
- d
- The system which is to be reduced.
Methods
GenericSOBTpvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.sobt.SOBTvpReductor(d)[source]¶ Bases:
pymor.reductors.sobt.GenericSOBTpvReductorSecond-Order Balanced Truncation velocity-position reductor.
See [RS08].
Parameters
- d
- The system which is to be reduced.
Methods
GenericSOBTpvReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.reductors.sor_irka.SOR_IRKAReductor(d)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceSOR-IRKA reductor.
Parameters
- d
- SecondOrderSystem.
Methods
SOR_IRKAReductorreconstruct,reduceBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid-
reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, projection='orth', use_arnoldi=False, conv_crit='sigma', compute_errors=False, irka_options=None)[source]¶ Reduce using SOR-IRKA.
It uses IRKA as the intermediate reductor, to reduce from 2r to r poles. See Section 5.3.2 in [W12].
Parameters
- r
- Order of the reduced order model.
- sigma
Initial interpolation points (closed under conjugation).
If
None, interpolation points are log-spaced between 0.1 and 10. Ifsigmais anint, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of lengthr.sigmaandrd0cannot both be notNone.- b
Initial right tangential directions.
If
None, if is chosen as all ones. Ifbis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aVectorArrayof lengthrfromd.B.source.bandrd0cannot both be notNone.- c
Initial left tangential directions.
If
None, if is chosen as all ones. Ifcis anint, it is used as a seed to generate it randomly. Otherwise, it needs to be aVectorArrayof lengthrfromd.Cp.range.candrd0cannot both be notNone.- rd0
Initial reduced order model.
If
None, thensigma,b, andcare used. Otherwise, it needs to be anLTISystemof orderrand it is used to constructsigma,b, andc.- tol
- Tolerance for the convergence criterion.
- maxit
- Maximum number of iterations.
- num_prev
- Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of IRKA.
- force_sigma_in_rhp
- If
False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only the poles in the left half-plane are reflected. - projection
Projection method:
'orth': projection matrices are orthogonalized with respect to the Euclidean inner product'biorth': projection matrices are biorthogolized with respect to the E product
- conv_crit
Convergence criterion:
'sigma': relative change in interpolation points'h2': relative
distance of
reduced-order models
- compute_errors
Should the relative
-errors of
intermediate reduced order models be computed.Warning
Computing
-errors is expensive. Use
this option only if necessary.- irka_options
- Dict of options for IRKAReductor.reduce.
Returns
- rd
- Reduced
LTISystemmodel.
pymor.tools package¶
Submodules¶
-
class
pymor.tools.deprecated.Deprecated(alt='no alternative given')[source]¶ Bases:
objectThis is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
Methods
Deprecated__get__
-
pymor.tools.floatcmp.float_cmp(x, y, rtol=1e-14, atol=1e-14)[source]¶ Compare x and y component-wise for almost equality.
For scalars we define almost equality as
float_cmp(x,y) <=> |x - y| <= atol + |y|*rtol
Note
Numpy’s
allclosemethod uses the same definition but treats arrays containing infinities as close if the infinities are at the same places and all other entries are close. In our definition, arrays containing infinities can never be close which seems more appropriate in most cases.Parameters
- x, y
NumPy arraysto be compared. Have to be broadcastable to the same shape.- rtol
- The relative tolerance.
- atol
- The absolute tolerance.
Defaults
rtol, atol (see
pymor.core.defaults)
-
class
pymor.tools.frozendict.FrozenDict(*args, **kwargs)[source]¶ Bases:
dictAn immutable dictionary.
Methods
dictcopy,fromkeys,get,items,keys,values,__contains__,__getitem__,__sizeof__Attributes
FrozenDictclear,pop,popitem,setdefault,update
-
pymor.tools.inverse.inv_transposed_two_by_two(A)[source]¶ Efficiently compute the tranposed inverses of a
NumPy arrayof 2x2-matrices| retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).
-
pymor.tools.inverse.inv_two_by_two(A)[source]¶ Efficiently compute the inverses of a
NumPy arrayof 2x2-matrices| retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).
-
pymor.tools.io.SafeTemporaryFileName(name=None, parent_dir=None)[source]¶ Cross Platform safe equivalent of re-opening a NamedTemporaryFile Creates an automatically cleaned up temporary directory with a single file therein.
name: filename component, defaults to ‘temp_file’ dir: the parent dir of the new tmp dir. defaults to tempfile.gettempdir()
This module provides helper methods to use pyMOR in parallel with MPI.
Executing this module will run event_loop on all MPI ranks
except for rank 0 where either a given script is executed:
mpirun -n 16 python -m pymor.tools.mpi /path/to/script
or an interactive session is started:
mpirun -n 16 python -m pymor.tools.mpi
When IPython is available, an IPython kernel is started which the user can connect to by calling:
ipython console --existing file_name_printed_by_ipython.json
(Starting the IPython console directly will not work properly with most MPI implementations.) When IPython is not available, the builtin Python REPL is started.
When event_loop is running on the MPI ranks, call
can be used on rank 0 to execute the same Python function (given
as first argument) simultaneously on all MPI ranks (including
rank 0). Calling quit will exit event_loop on
all MPI ranks.
Additionally, this module provides several helper methods which are
intended to be used in conjunction with call: mpi_info
will print a summary of all active MPI ranks, run_code
will execute the given code string on all MPI ranks,
import_module imports the module with the given path.
A simple object management is implemented with the
manage_object, get_object and remove_object
methods. It is the user’s responsibility to ensure that calls to
manage_object are executed in the same order on all MPI ranks
to ensure that the returned ObjectId refers to the same
distributed object on all ranks. The functions function_call,
function_call_manage, method_call,
method_call_manage map instances ObjectId
transparently to distributed objects. function_call_manage and
method_call_manage will call manage_object on the
return value and return the corresponding ObjectId. The functions
method_call and method_call_manage are given an
ObjectId and a string as first and second argument and execute
the method named by the second argument on the object referred to by the
first argument.
-
class
pymor.tools.mpi.ObjectId[source]¶ Bases:
intA handle to an MPI distributed object.
Methods
intbit_length,conjugate,from_bytes,to_bytes,__ceil__,__floor__,__new__,__round__,__sizeof__,__trunc__Attributes
intdenominator,imag,numerator,real
-
pymor.tools.mpi.call(method, *args, **kwargs)[source]¶ Execute method on all MPI ranks.
Assuming
event_loopis running on all MPI ranks (except rank 0), this will executemethodon all ranks (including rank 0) with positional argumentsargsand keyword argumentskwargs.Parameters
- method
- The function to execute on all ranks (must be picklable).
- args
- The positional arguments for
method. - kwargs
- The keyword arguments for
method.
Returns
The return value of
methodon rank 0.
-
pymor.tools.mpi.event_loop()[source]¶ Launches an MPI-based event loop.
Events can be sent by either calling
callon rank 0 to execute an arbitrary method on all ranks or by callingquitto exit the loop.
-
pymor.tools.mpi.event_loop_settings(auto_launch=True)[source]¶ Settings for pyMOR’s MPI event loop.
Parameters
- auto_launch
- If
True, automatically executeevent_loopon all MPI ranks (except 0) when pyMOR is imported.
Defaults
auto_launch (see
pymor.core.defaults)
-
pymor.tools.mpi.function_call(f, *args, **kwargs)[source]¶ Execute the function
fwith given arguments.Intended to be used in conjunction with
call. Arguments of typeObjectIdare transparently mapped to the object they refer to.
-
pymor.tools.mpi.function_call_manage(f, *args, **kwargs)[source]¶ Execute the function
fand manage the return value.Intended to be used in conjunction with
call. The return value offis managed by callingmanage_objectand the correspondingObjectIdis returned. Arguments of typeObjectIdare transparently mapped to the object they refer to.
-
pymor.tools.mpi.import_module(path)[source]¶ Import the module named by
path.Intended to be used in conjunction with
call.
-
pymor.tools.mpi.method_call(obj_id, name_, *args, **kwargs)[source]¶ Execute a method with given arguments.
Intended to be used in conjunction with
call. Arguments of typeObjectIdare transparently mapped to the object they refer to.Parameters
- obj_id
- The
ObjectIdof the object on which to call the method. name_- Name of the method to call.
- args
- Positional arguments for the method.
- kwargs
- Keyword arguments for the method.
-
pymor.tools.mpi.method_call_manage(obj_id, name_, *args, **kwargs)[source]¶ Execute a method with given arguments and manage the return value.
Intended to be used in conjunction with
call. The return value of the called method is managed by callingmanage_objectand the correspondingObjectIdis returned. Arguments of typeObjectIdare transparently mapped to the object they refer to.Parameters
- obj_id
- The
ObjectIdof the object on which to call the method. name_- Name of the method to call.
- args
- Positional arguments for the method.
- kwargs
- Keyword arguments for the method.
-
pymor.tools.mpi.mpi_info()[source]¶ Print some information on the MPI setup.
Intended to be used in conjunction with
call.
-
pymor.tools.mpi.quit()[source]¶ Exit the event loop on all MPI ranks.
This will cause
event_loopto terminate on all MPI ranks.
-
pymor.tools.mpi.remove_object(obj_id)[source]¶ Remove the object referred to by
obj_idfrom the registry.
-
pymor.tools.pprint.format_array(array, compact_print=False)[source]¶ Creates a formatted string representation of a
NumPy array.Parameters
- array
- the
NumPy arrayto be formatted - compact_print
- If
True, return a shorter version of string representation.
Returns
The string representation.
Defaults
compact_print (see
pymor.core.defaults)
-
class
pymor.tools.quadratures.GaussQuadratures[source]¶ Bases:
objectGauss quadrature on the interval [0, 1]
Methods
GaussQuadraturesiter_quadrature,maxpoints,quadratureAttributes
GaussQuadraturesa,order_map,orders,points,weights
-
pymor.tools.random.new_random_state(seed=42)[source]¶ Returns a new
NumPyRandomState.Parameters
- seed
- Seed to use for initializing the random state.
Returns
New
RandomStateobject.Defaults
seed (see
pymor.core.defaults)
-
class
pymor.tools.timing.Timer(section, log=<Logger pymor.tools.timing (INFO)>)[source]¶ Bases:
objectYou can use me as a context manager, plain instance or decorator to time execution of a code scope:
with Timer() as timer: do_some_stuff() do more stuff() #outputs time in (s) ### OR ### @timing.Timer('name', logging.debug) def function(*args): do_stuff function(1) #outputs time in (s) to logging.debug ### OR ### timer = timing.Timer() timer.start() do_stuff() timer.stop() print(timer.dt)
Methods
Timerstart,stop
-
pymor.tools.vtkio.write_vtk(grid, data, filename_base, codim=2, binary_vtk=True, last_step=None)[source]¶ Output grid-associated data in (legacy) vtk format
Parameters
- grid
- A
Gridwith triangular or rectilinear reference element. - data
VectorArraywith either cell (ie one datapoint per codim 0 entity) or vertex (ie one datapoint per codim 2 entity) data in each array element.- codim
- the codimension associated with the data
- filename_base
- common component for output files in timeseries
- binary_vtk
- if false, output files contain human readable inline ascii data, else appended binary
- last_step
- if set must be <= len(data) to restrict output of timeseries
pymor.vectorarrays package¶
Submodules¶
-
class
pymor.vectorarrays.block.BlockVectorArray(blocks, space)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArraywhere each vector is a direct sum of sub-vectors.Given a list of equal length
VectorArraysblocks, thisVectorArrayrepresents the direct sums of the vectors contained in the arrays. The associatedVectorSpaceisBlockVectorSpace.BlockVectorArraycan be used in conjunction withBlockOperator.Methods
Attributes
BlockVectorArrayimag,num_blocks,realVectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
copy(deep=False)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
imag¶ Imaginary part.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
real¶ Real part.
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
sup_norm()[source]¶ The l-infinity-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
to_numpy(ensure_copy=False)[source]¶ Return (len(self), self.dim) NumPy Array with the data stored in the array.
Parameters
- ensure_copy
- If
False, modifying the returnedNumPy arraymight alter the originalVectorArray. IfTruealways a copy of the array data is made.
-
-
class
pymor.vectorarrays.block.BlockVectorArrayView(base, ind)[source]¶ Bases:
pymor.vectorarrays.block.BlockVectorArrayMethods
Attributes
BlockVectorArrayViewis_viewBlockVectorArrayimag,num_blocks,realVectorArrayInterfacedata,dim,spaceBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.vectorarrays.block.BlockVectorSpace(subspaces, id_=None)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorSpaceInterfaceVectorSpaceofBlockVectorArrays.A
BlockVectorSpaceis defined by theVectorSpacesof the individual subblocks which constitute a given array. In particular for a given :class`BlockVectorArray`U, we have the identity(U.blocks[0].space, U.blocks[1].space, ..., U.blocks[-1].space) == U.space.
Parameters
- subspaces
- The tuple defined above.
Methods
BlockVectorSpacefrom_numpy,make_array,make_block_diagonal_array,zerosVectorSpaceInterfaceempty,from_dataImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BlockVectorSpacedimVectorSpaceInterfaceid,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
from_numpy(data, ensure_copy=False)[source]¶ Create a
VectorArrayfrom aNumPy arrayNote that this method will not be supported by all vector space implementations.
Parameters
- data
NumPyarray of shape(len, dim)wherelenis the number of vectors anddimtheir dimension.- ensure_copy
- If
False, modifying the returnedVectorArraymight alter the originalNumPy array. IfTruealways a copy of the array data is made.
Returns
A
VectorArraywithdataas data.
-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
pymor.vectorarrays.constructions.cat_arrays(vector_arrays)[source]¶ Return a new
VectorArraywhich is a concatenation of the arrays invector_arrays.
-
class
pymor.vectorarrays.interfaces.VectorArrayInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for vector arrays.
A vector array should be thought of as a list of (possibly high-dimensional) vectors. While the vectors themselves will be inaccessible in general (e.g. because they are managed by an external PDE solver code), operations on the vectors like addition can be performed via this interface.
It is assumed that the number of vectors is small enough such that scalar data associated to each vector can be handled on the Python side. As such, methods like
l2_normorgramianwill always returnNumPy arrays.An implementation of the
VectorArrayInterfaceviaNumPy arraysis given byNumpyVectorArray. In general, it is the implementors decision how memory is allocated internally (e.g. continuous block of memory vs. list of pointers to the individual vectors.) Thus, no general assumptions can be made on the costs of operations like appending to or removing vectors from the array. As a hint for ‘continuous block of memory’ implementations,zerosprovides areservekeyword argument which allows to specify to what size the array is assumed to grow.As with
NumPy array,VectorArrayscan be indexed with numbers, slices and lists or one-dimensionalNumPy arrays. Indexing will always return a newVectorArraywhich acts as a view into the original data. Thus, if the indexed array is modified viascaloraxpy, the vectors in the original array will be changed. Indices may be negative, in which case the vector is selected by counting from the end of the array. Moreover indices can be repeated, in which case the corresponding vector is selected several times. The resulting view will be immutable, however.Note
It is disallowed to append vectors to a
VectorArrayview or to remove vectors from it. Removing vectors from an array with existing views will lead to undefined behavior of these views. As such, it is generally advisable to make acopyof a view for long term storage. Sincecopyhas copy-on-write semantics, this will usually cause little overhead.Methods
Attributes
VectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
dim¶ The dimension of the vectors in the array.
-
is_view¶ Trueif the array is a view obtained by indexing another array.
-
space¶ The
VectorSpacethe array belongs to.
-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
check_ind(ind)[source]¶ Check if
indis an admissible list of indices in the sense of the class documentation.
-
check_ind_unique(ind)[source]¶ Check if
indis an admissible list of non-repeated indices in the sense of the class documentation.
-
copy(deep=False)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
empty(reserve=0)[source]¶ Create an empty
VectorArrayof the sameVectorSpace.This is a shorthand for
self.space.zeros(0, reserve).Parameters
- reserve
- Hint for the backend to which length the array will grow.
Returns
An empty
VectorArray.
-
inner(other, product=None)[source]¶ Inner products w.r.t. given product
Operator.Equivalent to
self.dot(other)ifproductis None, else equivalent toproduct.apply2(self, other).
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
norm(product=None)[source]¶ Norm w.r.t. given inner product
Operator.Equivalent to
self.l2_norm()ifproductis None, else equivalent tonp.sqrt(product.pairwise_apply2(self, self)).
-
norm2(product=None)[source]¶ Squared norm w.r.t. given inner product
Operator.Equivalent to
self.l2_norm2()ifproductis None, else equivalent toproduct.pairwise_apply2(self, self).
-
normalize_ind(ind)[source]¶ Normalize given indices such that they are independent of the array length.
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
pairwise_inner(other, product=None)[source]¶ Pairwise inner products w.r.t. given product
Operator.Equivalent to
self.pairwise_dot(other)ifproductis None, else equivalent toproduct.pairwise_apply2(self, other).
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
sup_norm()[source]¶ The l-infinity-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
to_numpy(ensure_copy=False)[source]¶ Return (len(self), self.dim) NumPy Array with the data stored in the array.
Parameters
- ensure_copy
- If
False, modifying the returnedNumPy arraymight alter the originalVectorArray. IfTruealways a copy of the array data is made.
-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectors of the sameVectorSpace.This is a shorthand for
self.space.zeros(count, reserve).Parameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
-
class
pymor.vectorarrays.interfaces.VectorSpaceInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceClass describing a vector space.
Vector spaces act as factories for
VectorArraysof vectors contained in them. As such, they hold all data necessary to createVectorArraysof a given type (e.g. the dimension of the vectors, or a socket for communication with an external PDE solver).New
VectorArraysof null vectors are created viazeros. Themake_arraymethod builds a newVectorArrayfrom given raw data of the underlying linear algebra backend (e.g. aNumPy arrayin the case ofNumpyVectorSpace). Some vector spaces can create newVectorArraysfrom a givenNumPy arrayvia thefrom_numpymethod.Each vector space has a string
idto distinguish mathematically different spaces appearing in the formulation of a given problem.Vector spaces can be compared for equality via the
==and!=operators. To test if a givenVectorArrayis an element of the space, theinoperator can be used.Methods
Attributes
VectorSpaceInterfacedim,id,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
id¶ None, or a string describing the mathematical identity of the vector space (for instance to distinguish different components in an equation system).
-
dim¶ The dimension (number of degrees of freedom) of the vectors contained in the space.
-
is_scalar¶ Equivalent to
isinstance(space, NumpyVectorSpace) and space.dim == 1.
-
empty(reserve=0)[source]¶ Create an empty
VectorArrayThis is a shorthand for
self.zeros(0, reserve).Parameters
- reserve
- Hint for the backend to which length the array will grow.
Returns
An empty
VectorArray.
-
from_numpy(data, ensure_copy=False)[source]¶ Create a
VectorArrayfrom aNumPy arrayNote that this method will not be supported by all vector space implementations.
Parameters
- data
NumPyarray of shape(len, dim)wherelenis the number of vectors anddimtheir dimension.- ensure_copy
- If
False, modifying the returnedVectorArraymight alter the originalNumPy array. IfTruealways a copy of the array data is made.
Returns
A
VectorArraywithdataas data.
-
make_array(**kwargs)[source]¶ Create a
VectorArrayfrom raw data.This method is used in the implementation of
OperatorsandDiscretizationsto create newVectorArraysfrom raw data of the underlying solver backends. The ownership of the data is transferred to the newly created array.The exact signature of this method depends on the wrapped solver backend.
-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
-
class
pymor.vectorarrays.list.CopyOnWriteVector[source]¶ Bases:
pymor.vectorarrays.list.VectorInterfaceMethods
CopyOnWriteVectoraxpy,copy,from_instance,scalVectorInterfaceamax,dofs,dot,l1_norm,l2_norm,l2_norm2,sup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.vectorarrays.list.ListVectorArray(vectors, space)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArrayimplemented as a Python list of vectors.This
VectorArrayimplementation is the first choice when creating pyMOR wrappers for external solvers which are based on single vector objects. In order to do so, a wrapping subclass ofVectorInterfacehas to be provided on which the implementation ofListVectorArraywill operate. The associatedVectorSpaceis a subclass ofListVectorSpace.For an example, see
NumpyVector,NumpyListVectorSpaceorFenicsVector,FenicsVectorSpace.Methods
Attributes
VectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
copy(deep=False)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
sup_norm()[source]¶ The l-infinity-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
to_numpy(ensure_copy=False)[source]¶ Return (len(self), self.dim) NumPy Array with the data stored in the array.
Parameters
- ensure_copy
- If
False, modifying the returnedNumPy arraymight alter the originalVectorArray. IfTruealways a copy of the array data is made.
-
-
class
pymor.vectorarrays.list.ListVectorArrayView(base, ind)[source]¶ Bases:
pymor.vectorarrays.list.ListVectorArrayMethods
Attributes
ListVectorArrayViewis_view,spaceVectorArrayInterfacedata,dimBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
-
class
pymor.vectorarrays.list.ListVectorSpace[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorSpaceInterfaceVectorSpaceofListVectorArrays.Methods
ListVectorSpacefrom_numpy,make_array,make_vector,space_from_dim,space_from_vector_obj,vector_from_numpy,zero_vector,zerosVectorSpaceInterfaceempty,from_dataImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
ListVectorSpacedimVectorSpaceInterfaceid,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
-
class
pymor.vectorarrays.list.NumpyListVectorSpace(dim, id_=None)[source]¶ Bases:
pymor.vectorarrays.list.ListVectorSpaceMethods
NumpyListVectorSpacemake_vector,space_from_dim,space_from_vector_obj,vector_from_numpy,zero_vectorListVectorSpacefrom_numpy,make_array,zerosVectorSpaceInterfaceempty,from_dataImmutableInterfacegenerate_sid,with_,__setattr__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors
-
class
pymor.vectorarrays.list.NumpyVector(array)[source]¶ Bases:
pymor.vectorarrays.list.CopyOnWriteVectorVector stored in a NumPy 1D-array.
Methods
NumpyVectoramax,dofs,dot,from_instance,l1_norm,l2_norm,l2_norm2,to_numpyCopyOnWriteVectoraxpy,copy,scalVectorInterfacesup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
NumpyVectordimBasicInterfacelogger,logging_disabled,name,uid
-
class
pymor.vectorarrays.list.VectorInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for vectors used in conjunction with
ListVectorArray.This interface must be satisfied by the individual entries of the vector
listmanaged byListVectorArray. All interface methods have a direct counterpart in theVectorArrayinterface.Methods
VectorInterfaceamax,axpy,copy,dofs,dot,l1_norm,l2_norm,l2_norm2,scal,sup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementorsAttributes
BasicInterfacelogger,logging_disabled,name,uid
Wrapper classes for building MPI distributed VectorArrays.
This module contains several wrapper classes which allow to
transform single rank VectorArrays into MPI distributed
VectorArrays which can be used on rank 0 like ordinary
VectorArrays.
The implementations are based on the event loop provided
by pymor.tools.mpi.
-
class
pymor.vectorarrays.mpi.MPIVectorArray(obj_id, space)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceMPI distributed
VectorArray.Given a local
VectorArrayon each MPI rank, this wrapper class uses the event loop frompymor.tools.mpito build a global MPI distributed vector array from these local arrays.Instances of
MPIVectorArraycan be used on rank 0 like any other (non-distributed)VectorArray.Note, however, that the implementation of the local VectorArrays needs to be MPI aware. For instance,
cls.dotmust perform the needed MPI communication to sum up the local inner products and return the sums on rank 0.Default implementations for all communication requiring interface methods are provided by
MPIVectorArrayAutoComm(also seeMPIVectorArrayNoComm).Note that resource cleanup is handled by
object.__del__. Please be aware of the peculiarities of destructors in Python!The associated
VectorSpaceisMPIVectorSpace.Methods
Attributes
VectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
copy(deep=False)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
-
class
pymor.vectorarrays.mpi.MPIVectorArrayAutoComm(obj_id, space)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorArrayMPI distributed
VectorArray.This is a subclass of
MPIVectorArraywhich provides default implementations for all communication requiring interface methods for the case when the wrapped array is not MPI aware.Note, however, that depending on the discretization these default implementations might lead to wrong results (for instance in the presence of shared DOFs).
The associated
VectorSpaceisMPIVectorSpaceAutoComm.Methods
Attributes
VectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
-
class
pymor.vectorarrays.mpi.MPIVectorArrayNoComm(obj_id, space)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorArrayMPI distributed
VectorArray.This is a subclass of
MPIVectorArraywhich overrides all communication requiring interface methods to raiseNotImplementedError.This is mainly useful as a security measure when wrapping arrays for which simply calling the respective method on the wrapped arrays would lead to wrong results and
MPIVectorArrayAutoCommcannot be used either (for instance in the presence of shared DOFs).The associated
VectorSpaceisMPIVectorSpaceNoComm.Methods
Attributes
VectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
-
class
pymor.vectorarrays.mpi.MPIVectorSpace(local_spaces)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorSpaceInterfaceVectorSpaceofMPIVectorArrays.Parameters
- local_spaces
tupleof the differentVectorSpacesof the localVectorArrayson the MPI ranks. Alternatively, the length oflocal_spacesmay be 1, in which case the sameVectorSpaceis assumed for all ranks.
Methods
Attributes
MPIVectorSpacearray_type,dimVectorSpaceInterfaceid,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
array_type¶ alias of
MPIVectorArray
-
make_array(obj_id)[source]¶ Create array from rank-local
VectorArrayinstances.Parameters
- obj_id
ObjectIdof the MPI distributed instances ofclswrapped by this array.
Returns
The newly created : class:
MPIVectorArray.
-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
class
pymor.vectorarrays.mpi.MPIVectorSpaceAutoComm(local_spaces)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorSpaceVectorSpaceforMPIVectorArrayAutoComm.Methods
Attributes
MPIVectorSpaceAutoCommarray_type,dimVectorSpaceInterfaceid,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
array_type¶ alias of
MPIVectorArrayAutoComm
-
-
class
pymor.vectorarrays.mpi.MPIVectorSpaceNoComm(local_spaces)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorSpaceVectorSpaceforMPIVectorArrayNoComm.Methods
Attributes
MPIVectorSpaceNoCommarray_type,dimVectorSpaceInterfaceid,is_scalarImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
array_type¶ alias of
MPIVectorArrayNoComm
-
-
class
pymor.vectorarrays.numpy.NumpyVectorArray(array, space)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArrayimplementation viaNumPy arrays.This is the default
VectorArraytype used by allOperatorsin pyMOR’s discretization toolkit. Moreover, all reducedOperatorsare based onNumpyVectorArray.This class is just a thin wrapper around the underlying
NumPy array. Thus, while operations likeaxpyordotwill be quite efficient, removing or appending vectors will be costly.The associated
VectorSpaceisNumpyVectorSpace.Methods
Attributes
NumpyVectorArrayimag,realVectorArrayInterfacedata,dim,is_view,spaceBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax(*, _ind=None)[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, *, _ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
copy(deep=False, *, _ind=None)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices, *, _ind=None)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other, *, _ind=None)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
imag¶ Imaginary part.
-
l1_norm(*, _ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm(*, _ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2(*, _ind=None)[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients, *, _ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, *, _ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
real¶ Real part.
-
scal(alpha, *, _ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
sup_norm(*, _ind=None)[source]¶ The l-infinity-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
to_numpy(ensure_copy=False)[source]¶ Return (len(self), self.dim) NumPy Array with the data stored in the array.
Parameters
- ensure_copy
- If
False, modifying the returnedNumPy arraymight alter the originalVectorArray. IfTruealways a copy of the array data is made.
-
-
class
pymor.vectorarrays.numpy.NumpyVectorArrayView(array, ind)[source]¶ Bases:
pymor.vectorarrays.numpy.NumpyVectorArrayMethods
Attributes
NumpyVectorArrayViewis_viewNumpyVectorArrayimag,realVectorArrayInterfacedata,dim,spaceBasicInterfacelogger,logging_disabled,name,uid-
__getitem__(ind)[source]¶ Return a
VectorArrayview onto a subset of the vectors in the array.
-
amax()[source]¶ The maximum absolute value of the DOFs contained in the array.
Returns
- max_ind
NumPy arraycontaining for each vector a DOF index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its DOFs.
-
append(other, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x)[source]¶ BLAS AXPY operation.
This method forms the sum
self = alpha*x + self
If the length of
xis 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofselfandxhave to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands.
-
copy(deep=False)[source]¶ Returns a copy of the array.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.Parameters
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dofs(dof_indices)[source]¶ Extract DOFs of the vectors contained in the array.
Parameters
- dof_indices
- List or 1D
NumPy arrayof indices of the DOFs that are to be returned.
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thedof_indices[j]-th DOF of thei-th vector of the array.
-
dot(other)[source]¶ Returns the inner products between
VectorArrayelements.In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.
Parameters
- other
- A
VectorArraycontaining the second factors.
-
l1_norm()[source]¶ The l1-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm()[source]¶ The l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
l2_norm2()[source]¶ The squared l2-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
lincomb(coefficients)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors.
-
scal(alpha)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self = alpha*self
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asselfcontaining the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied.
-
sup_norm()[source]¶ The l-infinity-norms of the vectors contained in the array.
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[i].
-
to_numpy(ensure_copy=False)[source]¶ Return (len(self), self.dim) NumPy Array with the data stored in the array.
Parameters
- ensure_copy
- If
False, modifying the returnedNumPy arraymight alter the originalVectorArray. IfTruealways a copy of the array data is made.
-
-
class
pymor.vectorarrays.numpy.NumpyVectorSpace(dim, id_=None)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorSpaceInterfaceVectorSpaceofNumpyVectorArrays.Parameters
- dim
- The dimension of the vectors contained in the space.
- id
- See
id.
Methods
Attributes
NumpyVectorSpaceis_scalarVectorSpaceInterfacedim,idImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelogger,logging_disabled,name,uid-
is_scalar¶ bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
-
zeros(count=1, reserve=0)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
- reserve
- Hint for the backend to which length the array will grow.
Returns
A
VectorArraycontainingcountvectors with each component zero.
Demo Applications¶
pymordemos package¶
Submodules¶
analyze_pickle module¶
Analyze pickled data demo.
- Usage:
- analyze_pickle.py histogram [–detailed=DETAILED_DATA] [–error-norm=NORM] REDUCED_DATA SAMPLES analyze_pickle.py convergence [–detailed=DETAILED_DATA] [–error-norm=NORM] [–ndim=NDIM] REDUCED_DATA SAMPLES analyze_pickle.py (-h | –help)
This demo loads a pickled reduced discretization, solves for random parameters, estimates the reduction errors and then visualizes these estimates. If the detailed discretization and the reductor are also provided, the estimated error is visualized in comparison to the real reduction error.
The needed data files are created by the thermal block demo, by setting the ‘–pickle’ option.
- Arguments:
REDUCED_DATA File containing the pickled reduced discretization.
SAMPLES Number of parameter samples to test with.
- Options:
--detailed=DETAILED_DATA File containing the high-dimensional discretization and the reductor. --error-norm=NORM Name of norm in which to compute the errors. --ndim=NDIM Number of reduced basis dimensions for which to estimate the error.
-
pymordemos.analyze_pickle._bins(start, stop, steps=100)[source]¶ numpy has a quirk in unreleased master where logspace might sometimes not return a 1d array
burgers module¶
Burgers demo.
Solves a two-dimensional Burgers-type equation. See pymor.analyticalproblems.burgers for more details.
- Usage:
- burgers.py [-h] [–grid=NI] [–grid-type=TYPE] [–initial-data=TYPE] [–lxf-lambda=VALUE] [–nt=COUNT]
- [–not-periodic] [–num-flux=FLUX] [–vx=XSPEED] [–vy=YSPEED] EXP
- Arguments:
- EXP Exponent
- Options:
--grid=NI Use grid with (2*NI)*NI elements [default: 60]. --grid-type=TYPE Type of grid to use (rect, tria) [default: rect]. --initial-data=TYPE Select the initial data (sin, bump) [default: sin] --lxf-lambda=VALUE Parameter lambda in Lax-Friedrichs flux [default: 1]. --nt=COUNT Number of time steps [default: 100]. --not-periodic Solve with dirichlet boundary conditions on left and bottom boundary. --num-flux=FLUX Numerical flux to use (lax_friedrichs, engquist_osher) [default: engquist_osher]. -h, --help Show this message. --vx=XSPEED Speed in x-direction [default: 1]. --vy=YSPEED Speed in y-direction [default: 1].
burgers_ei module¶
Burgers with EI demo.
Model order reduction of a two-dimensional Burgers-type equation (see pymor.analyticalproblems.burgers) using the reduced basis method with empirical operator interpolation.
- Usage:
- burgers_ei.py [options] EXP_MIN EXP_MAX EI_SNAPSHOTS EISIZE SNAPSHOTS RBSIZE
- Arguments:
EXP_MIN Minimal exponent
EXP_MAX Maximal exponent
EI_SNAPSHOTS Number of snapshots for empirical interpolation.
EISIZE Number of interpolation DOFs.
SNAPSHOTS Number of snapshots for basis generation.
RBSIZE Size of the reduced basis
- Options:
--cache-region=REGION Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: DISK] --ei-alg=ALG Interpolation algorithm to use (EI_GREEDY, DEIM) [default: EI_GREEDY]. --grid=NI Use grid with (2*NI)*NI elements [default: 60]. --grid-type=TYPE Type of grid to use (rect, tria) [default: rect]. --initial-data=TYPE Select the initial data (sin, bump) [default: sin] --lxf-lambda=VALUE Parameter lambda in Lax-Friedrichs flux [default: 1]. --not-periodic Solve with dirichlet boundary conditions on left and bottom boundary. --nt=COUNT Number of time steps [default: 100]. --num-flux=FLUX Numerical flux to use (lax_friedrichs, engquist_osher) [default: engquist_osher]. -h, --help Show this message. -p, --plot-err Plot error. --plot-ei-err Plot empirical interpolation error. --plot-error-landscape Calculate and show plot of reduction error vs. basis sizes. --plot-error-landscape-N=COUNT Number of basis sizes to test [default: 10] --plot-error-landscape-M=COUNT Number of collateral basis sizes to test [default: 10] --plot-solutions Plot some example solutions. --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --vx=XSPEED Speed in x-direction [default: 1]. --vy=YSPEED Speed in y-direction [default: 1]. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization.
elliptic module¶
Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.
- Usage:
- elliptic.py [–fv] [–rect] PROBLEM-NUMBER DIRICHLET-NUMBER NEUMANN-NUMBER NEUMANN-COUNT
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
DIRICHLET-NUMBER {0,1,2}, selects the Dirichlet data function
NEUMANN-NUMBER {0,1}, selects the Neumann data function
- NEUMANN-COUNT 0: no neumann boundary
- 1: right edge is neumann boundary 2: right+top edges are neumann boundary 3: right+top+bottom edges are neumann boundary
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements. --rect Use RectGrid instead of TriaGrid.
elliptic2 module¶
Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.
- Usage:
- elliptic2.py [–fv] PROBLEM-NUMBER N
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
N Triangle count per direction
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements.
elliptic_oned module¶
Proof of concept for solving the Poisson equation in 1D using linear finite elements and our grid interface
- Usage:
- elliptic_oned.py [–fv] PROBLEM-NUMBER N
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
N Grid interval count
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements.
elliptic_unstructured module¶
Simple demonstration of solving the Poisson equation in 2D on a circular sector domain of radius 1 using an unstructured mesh.
Note that Gmsh (http://geuz.org/gmsh/) is required for meshing.
- Usage:
- elliptic_unstructured.py ANGLE NUM_POINTS CLSCALE
- Arguments:
ANGLE The angle of the circular sector.
NUM_POINTS The number of points that form the arc of the circular sector.
CLSCALE Mesh element size scaling factor.
- Options:
-h, --help Show this message.
hapod module¶
HAPOD demo.
Demonstrates compression of snapshot data with the HAPOD algorithm from [HLR18].
- Usage:
- hapod.py [options] TOL DIST INC
- Arguments:
- TOL Prescribed mean l2 approximation error. DIST Number of slices for distributed HAPOD. INC Number of steps for incremental HAPOD.
- Options:
--grid=NI Use grid with (2*NI)*NI elements [default: 60]. -h, --help Show this message. --nt=COUNT Number of time steps [default: 100]. --omega=OMEGA Parameter omega from HAPOD algorithm [default: 0.9]. --procs=PROCS Number of processes to use for parallelization [default: 0]. --snap=SNAP Number of snapshot trajectories to compute [default: 20]. --threads=THREADS Number of threads to use for parallelization [default: 0].
parabolic module¶
Simple demonstration of solving parabolic equations using pyMOR’s builtin discretization toolkit.
- Usage:
- parabolic.py [options] heat TOP parabolic.py [options] dar SPEED
- Arguments:
- TOP The heat diffusion coefficient for the top bars. SPEED The advection speed.
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements. --rect Use RectGrid instead of TriaGrid. --grid=NI Use grid with NIxNI intervals [default: 100]. --nt=COUNT Number of time steps [default: 100].
parabolic_mor module¶
Reduced basis approximation of the heat equation.
- Usage:
- parabolic_mor.py BACKEND ALG SNAPSHOTS RBSIZE TEST
- Arguments:
BACKEND Discretization toolkit to use (pymor, fenics).
- ALG The model reduction algorithm to use
- (greedy, adaptive_greedy, pod).
- SNAPSHOTS greedy/pod: number of training set parameters
- adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis.
TEST Number of test parameters for reduction error estimation.
thermalblock module¶
Thermalblock demo.
- Usage:
- thermalblock.py [options] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE thermalblock.py -h | –help
- Arguments:
XBLOCKS Number of blocks in x direction.
YBLOCKS Number of blocks in y direction.
SNAPSHOTS naive: ignored
- greedy/pod: Number of training_set parameters per block
- (in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).
adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis
- Options:
--adaptive-greedy-rho=RHO See pymor.algorithms.adaptivegreedy [default: 1.1]. --adaptive-greedy-gamma=GAMMA See pymor.algorithms.adaptivegreedy [default: 0.2]. --adaptive-greedy-theta=THETA See pymor.algorithms.adaptivegreedy [default: 0.] --alg=ALG The model reduction algorithm to use (naive, greedy, adaptive_greedy, pod) [default: greedy]. --cache-region=REGION Name of cache region to use for caching solution snapshots (none, memory, disk, persistent) [default: none]. --extension-alg=ALG Basis extension algorithm (trivial, gram_schmidt) to be used [default: gram_schmidt]. --fenics Use FEniCS discretization. --grid=NI Use grid with 4*NI*NI elements [default: 100]. -h, --help Show this message. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization. --list-vector-array Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray. --order=ORDER Polynomial order of the Lagrange finite elements to use in FEniCS discretization [default: 1]. --pickle=PREFIX Pickle reduced discretizaion, as well as reductor and high-dimensional discretization to files with this prefix. --plot-err Plot error. --plot-solutions Plot some example solutions. --plot-error-sequence Plot reduction error vs. basis size. --product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1]. --reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis] --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --greedy-without-estimator Do not use error estimator for basis generation.
-
pymordemos.thermalblock.discretize_fenics(xblocks, yblocks, grid_num_intervals, element_order)[source]¶
-
pymordemos.thermalblock.discretize_pymor(xblocks, yblocks, grid_num_intervals, use_list_vector_array)[source]¶
-
pymordemos.thermalblock.reduce_adaptive_greedy(d, reductor, validation_mus, extension_alg_name, max_extensions, use_estimator, rho, gamma, theta, pool)[source]¶
-
pymordemos.thermalblock.reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool)[source]¶
thermalblock_adaptive module¶
Modified thermalblock demo using adaptive greedy basis generation algorithm.
- Usage:
- thermalblock_adaptive.py [options] RBSIZE thermalblock_adaptive.py -h | –help
- Arguments:
- RBSIZE Size of the reduced basis
- Options:
-h, --help Show this message. --without-estimator Do not use error estimator for basis generation. --extension-alg=ALG Basis extension algorithm (trivial, gram_schmidt) to be used [default: gram_schmidt]. --grid=NI Use grid with 2*NI*NI elements [default: 100]. --pickle=PREFIX Pickle reduced discretizaion, as well as reductor and high-dimensional discretization to files with this prefix. -p, --plot-err Plot error. --plot-solutions Plot some example solutions. --plot-error-sequence Plot reduction error vs. basis size. --product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1]. --reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis] --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization. --cache-region=REGION Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: NONE] --list-vector-array Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray. --no-visualize-refinement Do not visualize the training set refinement indicators. --validation-mus=VALUE Size of validation set. [default: 0] --rho=VALUE Maximum allowed ratio between error on validation set and on training set [default: 1.1]. --gamma=VALUE Weight factor for age penalty term in refinement indicators [default: 0.2]. --theta=VALUE Ratio of elements to refine [default: 0.].
thermalblock_gui module¶
Thermalblock with GUI demo
- Usage:
- thermalblock_gui.py [-h] [–product=PROD] [–grid=NI] [–testing]
- [–help] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE
- Arguments:
XBLOCKS Number of blocks in x direction.
YBLOCKS Number of blocks in y direction.
- SNAPSHOTS Number of snapshots for basis generation per component.
- In total SNAPSHOTS^(XBLOCKS * YBLOCKS).
RBSIZE Size of the reduced basis
- Options:
--grid=NI Use grid with 2*NI*NI elements [default: 60]. --product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1]. --testing load the gui and exit right away (for functional testing) -h, --help Show this message.
-
class
pymordemos.thermalblock_gui.AllPanel(parent, reduced_sim, detailed_sim)[source]¶ Bases:
object
-
class
pymordemos.thermalblock_gui.DetailedSim(args)[source]¶ Bases:
pymordemos.thermalblock_gui.SimBaseMethods
DetailedSimsolve
-
class
pymordemos.thermalblock_gui.ParamRuler(parent, sim)[source]¶ Bases:
objectMethods
ParamRulerenable
-
class
pymordemos.thermalblock_gui.ReducedSim(args)[source]¶ Bases:
pymordemos.thermalblock_gui.SimBaseMethods
ReducedSimsolve
thermalblock_simple module¶
Simplified version of the thermalblock demo.
- Usage:
- thermalblock_simple.py MODEL ALG SNAPSHOTS RBSIZE TEST
- Arguments:
MODEL High-dimensional model (pymor, fenics, ngsolve, pymor-text).
- ALG The model reduction algorithm to use
- (naive, greedy, adaptive_greedy, pod).
SNAPSHOTS naive: ignored
- greedy/pod: Number of training_set parameters per block
- (in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).
adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis.
TEST Number of parameters for stochastic error estimation.
-
pymordemos.thermalblock_simple.reduce_adaptive_greedy(d, reductor, validation_mus, basis_size)[source]¶

is the input and
is the output.